async await 异步运行

发布时间 2023-05-04 19:32:31作者: double64

测试代码:

class Program
{
    static void Main(string[] args)
    {
        TestAsync testAsync = new TestAsync();
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        Task<bool> resOne = testAsync.DoOne();
        Task<bool> resTwo = testAsync.DoTwo();
        Task.WaitAll(resOne, resTwo);
        stopwatch.Stop();
        Console.WriteLine($"耗时{stopwatch.Elapsed.TotalSeconds}");
        Console.WriteLine($"结果{resOne.Result} {resTwo.Result}");

        Console.ReadKey();
    }
}


public class TestAsync
{
    public async Task<bool> DoOne()
    {
        Console.WriteLine("进入 DoOne");
        bool res = await Task.Run(() =>
        {
            Thread.Sleep(1000);
            return false;
        });

        return res;
    }

    public async Task<bool> DoTwo()
    {
        Console.WriteLine("进入 DoTwo");
        bool res = await Task.Run(() =>
        {
            Thread.Sleep(2000);
            return true;
        });

        return res;
    }
}

测试结果:

进入 DoOne
进入 DoTwo
耗时2.0412127
结果False True