Is having a return type of Task enough to make a method run asynchronously?

后端 未结 3 1467
悲哀的现实
悲哀的现实 2020-12-12 07:46

I have a simple method that does a complicated string operation and returns the result. As you can see, the return type of this method is Task. Th

3条回答
  •  悲&欢浪女
    2020-12-12 08:24

    Based on your comments you need to do something like this:

    public Task ComplexOperation()
    {
        return Task.Run(() =>  /* Do something complex */);
    }
    

    You can play with it like this:

    public static async Task Main()
    {
        Console.WriteLine("Before" );
        var myResultTask = ComplexOperation();
        Console.WriteLine("After task creation");
        var result = await myResultTask;
        Console.WriteLine("After async await");
    }
    
    public Task ComplexOperation()
    {    
        Console.WriteLine("Creation");
        return Task.Run(() =>
        {
            Console.WriteLine("In before work");
            Thread.Sleep(500); //simulate work;
            Console.WriteLine("In after work");
            return "Done";
        });
    }
    

    And compare the behavior with switching to your implementation when you just return Task.FromResult. Also it does not makes much sense in such test example, TBH.

提交回复
热议问题