C#中的异步方法不是异步的吗? [英] async method in C# not asynchronous?

查看:120
本文介绍了C#中的异步方法不是异步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建了以下控制台应用程序后,我有些困惑,为什么它似乎是同步运行而不是异步运行:

Having created the following console application I am a little puzzled why it seems to run synchronously instead of asynchronously:

class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        var total = CreateMultipleTasks();
        stopwatch.Stop();

        Console.WriteLine("Total jobs done: {0} ms", total.Result);
        Console.WriteLine("Jobs done in: {0} ms", stopwatch.ElapsedMilliseconds);
    }

    static async Task<int> CreateMultipleTasks()
    {
        var task1 = WaitForMeAsync(5000);
        var task2 = WaitForMeAsync(3000);
        var task3 = WaitForMeAsync(4000);

        var val1 = await task1;
        var val2 = await task2;
        var val3 = await task3;

        return val1 + val2 + val3;

    }

    static Task<int> WaitForMeAsync(int ms)
    {
        Thread.Sleep(ms);
        return Task.FromResult(ms);
    }
}

运行该应用程序时,输出为:

When running the application, output is:

已完成的作业总数:12000毫秒
作业完成时间:12003毫秒

Total jobs done: 12000 ms
Jobs done in: 12003 ms

我原本希望这样:

已完成的作业总数:12000毫秒
作业完成时间:5003毫秒

Total jobs done: 12000 ms
Jobs done in: 5003 ms

这是因为当我使用Thread.Sleep方法时,它将停止整个应用程序的进一步执行吗?还是我在这里错过了重要的事情?

Is this because when I use the Thread.Sleep method it stops further execution of the whole application? Or am I missing something important here?

推荐答案

您以同步方式运行任务.您可以执行以下操作:

You run the task in a synchounus manner. You can do something like this:

static async Task<int> CreateMultipleTasks()
{
    var task1 = Task.Run<int>(() => WaitForMeAsync(5000));
    var task2 = Task.Run<int>(() => WaitForMeAsync(3000));
    var task3 = Task.Run<int>(() => WaitForMeAsync(4000));

    Task.WaitAll(new Task[] { task1, task2, task3 });

    return task1.Result + task2.Result + taks3.Result;

}

连续使用三个await不会并行运行任务.它只会在等待时释放线程(如果您使用await Task.Delay(ms),因为Thread.Sleep(ms)是阻塞操作),但是当task1处于睡眠"状态时,当前执行不会以task2继续.

Using the three await in a row will NOT run the tasks in parallel. It will just free the thread while it is waiting (if you use await Task.Delay(ms) as Thread.Sleep(ms) is a blocking operation), but the current execution will NOT continue with task2 while task1 is "sleeping".

这篇关于C#中的异步方法不是异步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆