Following program is designed using general Task.Run() and using async and await (asynchronous). In both cases a different Thread is taken from Thread pool for new task. So, what is the difference? Asynchronous means it should use the main thread and free it until task completed. But it is also using another thread rather than using main thread.
public class Worker2
{
public bool IsComplete { get; private set; }
internal void DoWork()
{
this.IsComplete = false;
Console.WriteLine("Doing Work.");
Task.Run(new Action(LongOperation));
Console.WriteLine("Work Completed");
IsComplete = true;
}
private void LongOperation()
{
Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);//Thread Id = 7. it is different from main thread id.
Console.WriteLine("Working!");
Thread.Sleep(3000);
}
}
//And asynchronous
public class Worker2
{
public bool IsComplete { get; private set; }
internal async void DoWork()
{
this.IsComplete = false;
Console.WriteLine("Doing Work.");
await LongOperation();
Console.WriteLine("Work Completed");
IsComplete = true;
}
private Task LongOperation()
{
return Task.Run(() =>
{
Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Working!");
Thread.Sleep(3000);
});
}
}
Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.
As you probably recall, await captures information about the current thread when used with Task. Run . It does that so execution can continue on the original thread when it is done processing on the other thread.
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.
You should use Task. Run , but not within any code you want to be reusable (i.e., library code). So you use Task. Run to call the method, not as part of the implementation of the method.
What is the difference between Task.Run() and await Task.Run()?
The first starts a task and then does the work immediately after that task, before the task completes.
The second starts a task and then does different work until the task is completed, at which point it does the work after the task.
Let's make an analogy. Your first program is like doing this:
Your second program is:
Clearly those are very different workflows. Both are asynchronous, but only the latter has an asynchronous wait in it. We asynchronously wait to tell the spouse that the lawn is mowed until it actually is mowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With