[英]C# synchronization between async tasks with infinite while loop?
I have one async task running an infinite loop doing some realtime processing: 我有一个异步任务运行无限循环做一些实时处理:
private async void RealTimeProcessingAsync()
{
while (true)
{
//....
Tmstaus status = await ReadStatusAsync();
switch (status)
{
case Ack:
//...
break;
//...
}
//...
}
}
And I created another async method SendWriteRqst that post command to RealTimeProcessingAsync(), should wait for status to set to defined condition and return. 我创建了另一个异步方法SendWriteRqst,它将命令发送到RealTimeProcessingAsync(),应该等待状态设置为已定义的条件并返回。
public async Task<WriteState> SendWriteRqstAsync(TmCommand tmCmd)
{
//...
await SomeCondition()//based on status value
//...
return wrState;
}
It will works if SomeCondition() runs another while loop to polling status and return true if conditions set, but I'm looking for better solution. 如果SomeCondition()运行另一个while循环到轮询状态并且如果条件设置则返回true,它将起作用,但我正在寻找更好的解决方案。
(Sorry for bad English) (抱歉英文不好)
It will works if SomeCondition() runs another while loop to polling status and return true if conditions set , but I'm looking for better solution.
如果SomeCondition()运行另一个while循环到轮询状态并且如果条件设置则返回true,它将起作用,但我正在寻找更好的解决方案。
What you want is a signal instead of a polling loop. 你想要的是一个信号而不是一个轮询循环。 If you only need to set the signal once, you can use
TaskCompletionSource<T>
. 如果您只需要设置一次信号,则可以使用
TaskCompletionSource<T>
。 If you want a signal that can be set and reset (without having to be reconstructed), then you can use AsyncManualResetEvent
(also available from NuGet in my AsyncEx.Coordination library ). 如果您想要一个可以设置和重置的信号(无需重建),那么您可以使用
AsyncManualResetEvent
(也可以从我的AsyncEx.Coordination库中的NuGet获得 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.