gpt4 book ai didi

c# - 异步和等待,有点困惑

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:25 27 4
gpt4 key购买 nike

我指的是 this解释 .Net framework 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!!!
}

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

最佳答案

我推荐我的 async intro对于 async 新手;它的末尾有指向最佳后续文档的链接。

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

附言不要在 async 代码中使用 Task 构造函数或 Task.Start;请改用 Task.Run

关于c# - 异步和等待,有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com