you will see a console app codes below. There are two situations I tried. In the first case, I commented await GetProducts() line. In this case, output is:
Start Time: 13:20:30 Job started... Finish Time: 13:20:30 Job finished...
In second case, I opened await GetProducts line and commented await Task.Run...lines. In this case, output is:
Start Time: 13:19:33 Job started... Job finished... Finish Time: 13:19:43
Here are the code lines...What is the difference? Thanks...
class Program
{
static void Main(string[] args)
{
Task x = LoadProductsAsync();
Console.Read();
}
private static async Task LoadProductsAsync()
{
Console.WriteLine("Start Time: " + DateTime.Now.ToLongTimeString());
//await GetProducts();
await Task.Run(() =>
{
GetProducts();
});
Console.WriteLine("Finish Time: " + DateTime.Now.ToLongTimeString());
}
private static Task<List<Product>> GetProducts()
{
return Task.Factory.StartNew(
() => GetProductsByCategory()
);
}
private static List<Product> GetProductsByCategory()
{
Console.WriteLine("Job started...");
System.Threading.Thread.Sleep(10000);
Console.WriteLine("Job finished...");
return new List<Product>();
}
}
This is the problem:
await Task.Run(() =>
{
GetProducts();
});
You're not waiting for the task returned by GetProducts()
to complete - you're just waiting for the immediate GetProducts()
method call to complete.
The simplest fix to that is to use a method group conversion instead, and call Task.Run<TResult>(Func<Task<TResult>>)
:
await Task.Run(GetProducts);
Then the task returned by Task.Run
will be a proxy task for the task returned by GetProducts()
, so the await
expression won't complete until GetProducts
has really finished.
See more on this question at Stackoverflow