简体   繁体   中英

Why await MethodName is working different from await Task.Run?

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.

Change your code to snnipet below. And your code will be the same.

await Task.Run(() =>
    {
        GetProductsByCategory();
    });

Your last code was like (you run task in task):

await Task.Run(() =>
    {
        return Task.Factory.StartNew(
            () => GetProductsByCategory()
        );
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM