Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Task.RunSynchronously for?

I just wonder what's the method for? In what kind of scenario I can use this method.

My initial thought is RunSynchronously is for calling an async method and running that synchronously without causing a deadlock issue like what .wait() does.

However, according to MSDN,

Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. Tasks executed by calling the RunSynchronously() method are associated with the current TaskScheduler and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the schedule, and the calling thread will block until the task has completed execution

Why need a TaskScheduler here, if the task going to run on the calling thread?

like image 336
ValidfroM Avatar asked Oct 11 '18 12:10

ValidfroM


People also ask

What is the purpose of Task run?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.

What is Task ASP NET core?

The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the . NET Framework 4.

What is Task in VB net?

In visual basic, Task is useful to perform the operations asynchronously on a thread pool threads and it was introduced in . NET Framework 4.0. To work with task objects, we need to import System.

Does Task run create new thread?

Starting a new task queues that task for execution on a threadpool thread. Threads execute in the context of the process (eg. the executable that runs your application). If this is a web application running under IIS, then that thread is created in the context of the IIS worker process.


1 Answers

RunSynchronously delegates the decision of when to start the task to the current task scheduler (or the one passed as argument).

I am not sure why it is there (maybe for internal or legacy use), but it is hard to think of a useful use case in the current versions of .NET. @Fabjan has a possible explanation in his comment to the question.

RunSynchronously asks the scheduler to run it synchronously but then the scheduler could very well ignore the hint and run it in a thread pool thread and your current thread will synchronously block until it is completed.

The scheduler does not have to run it on the current thread and does not have to run it immediately although I think it is what will happen on common schedulers (ThreadPoolTaskScheduler and common UI schedulers).

RunSynchronously will also throw an exception if the task has already been started or is completed/faulted (this means you will not be able to use it on async methods).

This code may clarify the different behaviour:

Wait and Result don't run the task at all, they just wait for the task completion on the current thread and block it until the completion so if we want to compare, we can compare Start and Wait to RunSynchronously:

class Scheduler : TaskScheduler {     protected override void QueueTask(Task task) =>          Console.WriteLine("QueueTask");      protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)     {         Console.WriteLine("TryExecuteTaskInline");          return false;     }      protected override IEnumerable<Task> GetScheduledTasks() => throw new NotImplementedException(); }  static class Program {     static void Main()     {         var taskToStart = new Task(() => { });         var taskToRunSynchronously = new Task(() => { });          taskToStart.Start(new Scheduler());         taskToRunSynchronously.RunSynchronously(new Scheduler());     } } 

If you try and comment Start or RunSynchronously and run the code, you will see that Start tries and queue the task to the scheduler while RunSynchronously will try and execute it inline and if failing (return false), it will just queue it.

like image 162
Stefano d'Antonio Avatar answered Oct 03 '22 22:10

Stefano d'Antonio