我正在编写一个程序,它可以与我设计的一些控制硬件进行通信。硬件驱动电机,我要做的第一件事就是初始化电机。硬件是通讯控制的,所以要做任何事情,我只需通过USB向硬件发送一条消息即可。要初始化马达,我必须发送两个消息;在我发送第一个消息后,它会将马达移动到传感器,当它到达传感器时,它会停止并向我发回一条消息,告诉我它已经停止,此时我会发送另一个消息,告诉它以相反的方向驱动马达,直到它从传感器出来。
我所有的通讯接收都是在SerialPort DataReceived活动中进行的。等待相关消息然后发送第二条消息的最佳方式是什么?目前,我只是使用bool类型的属性,在初始化之前我将其设置为true,然后在我的事件处理程序中,如果我收到通知电机已停止且bool为true的消息,我将bool设置为false并发送第二条消息。当它工作的时候,我想也许可以使用async和await?一般来说,这可能会更有效率一些?或者有没有其他更好的方法呢?任何反馈/指导都将非常感谢!
发布于 2016-05-17 19:59:35
在我看来,async-await的好处不是让你的调用者保持响应,而是你的代码看起来更容易,就好像它不是async-await。
也可以使用任务和ContinueWith语句,或者使用后台工作者或其他方法来创建线程,从而保持调用者的响应能力。但是如果你使用async await,你就不需要记住你的进程状态了,你现在可以通过设置布尔值来做这件事。
您的代码将如下所示:
public Task InitializeAsync(...)
{
await Send1stMessageAsync();
await Send2ndMessageAsync();
}In this article Eric Lippert explained async-await using a kitchen metaphor。发生的情况是,你的线程将做所有事情来发送第一条消息,直到它除了等待回复之外什么也做不了。然后将控制权交给第一个不等待的调用者。如果你没有等待,那就是你,例如,如果你有下面的代码:
public Task InitializeAsync(...)
{
var task1stMessage = Send1stMessageAsync();
// this thread will do everything inside Send1stMessageAsync until it sees an await.
// it then returns control to this function until there is an await here:
DoSomeThingElse();
// after a while you don't have anything else to do,
// so you wait until your first messages has been sent
// and the reply received:
await task1stMessage;
// control is given back to your caller who might have something
// useful to do until he awaits and control is given to his caller etc.
// when the await inside Send1stMessageAync is completed, the next statements inside
// Send1stMessageAsync are executed until the next await, or until the function completes.
var task2ndMessage = Send2ndMessageAsync();
DoSomethingUseful();
await task2ndMessage;
}您编写了使用事件通知线程数据已收到的代码。尽管让你的Send1stMessageAsync成为一个异步函数并不难,但你不需要重新发明轮子。考虑使用像SerialPortStream这样的nuget包来获取发送消息和等待回复的异步函数。
发布于 2016-05-16 23:26:19
如果您正在等待某些事情发生,并且您没有事件处理程序可供使用,那么使用异步/等待模式将是一个好主意
async Task WaitForCompletion()
{
await Task.Run(()=>
{
while(!theBoolVar)
Thread.Sleep(1000);
});
}然后在你的代码中使用
await WaitForCompletion();https://stackoverflow.com/questions/37256128
复制相似问题