What is the purpose of performing the task synchronously and when?

advertisements

what is the purpose of running task synchronously

public static void RunMeSync()
{
  for(int i = 0; i < 9999; i++)
  {
    ListBox1.Items.Add(i.ToString());
  }
}
public static void Main()
{
  Task T1 = new Task(()=>RunMeSync);
  T1.RunSynchronously();
  Task T2 = Task.Run(()=>RunMeSync);
}

is it pointless to do so ? what is the need to run task synchronously ?
Consider the following code snippet

public static void Main()
{
  Task T1 = new Task(()=>RunMeSync);
  T1.RunSynchronously();
  RunMeSync();
}

is it the same thing running T1 Synchronously, invoking RunMeSync directly?


Is it the same thing running T1 Synchronously, invoking RunMeSync directly?

Yes, the effect is going to be the same. You would not gain anything by running synchronously a task constructed from a method that you could call directly.

However, not all tasks are like that: some are constructed from methods to which you have no access - for example, tasks passed into your class as parameters. In other cases a task would have no named method associated with it, because it is constructed from a lambda or with an anonymous delegate. In all these cases, RunSynchronously() provides a way to calling the logic that implements the task, without knowing or worrying about the way in which that logic has been defined.