async 和 await ,有点混乱

use*_*747 2 c# multithreading asynchronous task-parallel-library c#-5.0

我正在参考这个博客,它解释了 .Net 框架 4.5 中 await 和 async 关键字的用法

我正在尝试使用这些关键字解决以下实时场景

我有两个设备 Device1 和 Device2。这些设备使用串行端口 (RS 232) 连接到我的计算机。我有一个 Windows 应用程序,它能够向这些设备发送命令。
现在,最初我必须通过发送特定的 RS-232 命令来启动这两个设备。现在我可以同时完成这项工作并相应地更新 UI。下面是解决这种情况的代码

public class Device1 
{
    public async Task<int> Start(int sec)
    {
        Console.WriteLine("Device1 started @ : " + DateTime.Now.ToString());
        Task t = new Task(() => { Thread.Sleep(sec * 1000); });
        t.Start();
        await t;
        Console.WriteLine("Device1 finished @ : " + DateTime.Now.ToString());
        return 1;
    }         
}

public class Device2 
{
    public async Task<int> Start(int sec)
    {
        Console.WriteLine("Device2 started @ : " + DateTime.Now.ToString());
        Task t = new Task(() => { Thread.Sleep(sec * 1000); });
        t.Start();
        await t;
        Console.WriteLine("Device2 finished @ : " + DateTime.Now.ToString());
        return 1;
    }       
}

private async void button1_Click(object sender, EventArgs e)
    {
        Device2 d2= new Device2();
        Device1 d1= new Device1();

        await d2.Start(10);
        label1.Text = "d2 Started....";///It takes 10 sec to update this
        await d1.Start(5);///this line starts executing after 10 secs?  Why?
        label1.Text = "d1 Started...";

        MessageBox.Show("I am done...");///Get this message after 15 sec!!!
    }
Run Code Online (Sandbox Code Playgroud)

现在,我的理解是这两个await d2.Start(10);await d1.Start(5);将同时运行,并会相应地更新UI。但事实并非如此。仔细查看 Console.WriteLine 语句证明它完全按顺序调用。
有人可以对此有更多的了解吗?

Ste*_*ary 5

我建议我async介绍async新手; 它在最后提供了最佳后续文档的链接。

简而言之,发生的事情是您正在await执行任务。这将暂停该方法,直到这些任务完成。如果您想让它们同时运行,那么您可以将任务保存到变量 ( t1, t2) 中,然后等待它们 ( await Task.WhenAll(t1, t2);)。

PS不要使用Task构造函数或Task.Startasync代码; 使用Task.Run来代替。