问题描述
我有主题:
- 具有Dispatcher循环的UI线程
- 在排队框架中侦听消息的后台线程.
收到消息后,将在后台线程中触发一个事件:
when a message is received, an event is fired in the background thread:
messageReceiver.Received += (sender, args) => ...
在UI线程中,我想等待一条消息,如下所示:
In UI thread I would like to await a message, something like this:
void ButtonClicked(object sender, RoutedEventArgs e) {
await NextMessage(); //should return when messageReceiver.Received is fired
}
如何实现等待的NextMessage方法,这样它就不会每次都创建新线程?
有一个SemaphoreSlim
类,我可以等待WaitAsync,但似乎会创建一个新线程,该线程在释放SemaphoreSlim之前会被阻塞.
There is SemaphoreSlim
class where I can await WaitAsync, but is seems to create new thread that is blocked until SemaphoreSlim is released.
也许TaskCompletionSource
是要走的路?那我应该使用哪个TaskCreationOption?
Maybe TaskCompletionSource
is the way to go? Which TaskCreationOption should I use then?
推荐答案
您提到了TaskCompletionSource
,我认为这就是您所需要的.您可以将其绑定到.Received
事件,如下所示:
You mentioned the TaskCompletionSource
and that is what I believe you need here. You'd tether it to the .Received
event like so:
static Task<IEnumerable<Message>> FromEvent(Receiver messageReceiver)
{
var tcs = new TaskCompletionSource<IEnumerable<Message>>();
EventHandler<IEnumerable<Message>> handler = null;
handler = (o, e) =>
{
messageReceiver.Received -= handler;
tcs.SetResult(e.Messages);
};
messageReceiver.Received += handler;
return tcs.Task;
}
然后您可以像这样等待它:
Then you could await it like this:
// Having the async keyword is fine here since this is an event handler
async void ButtonClicked(object sender, RoutedEventArgs e)
{
var messages = await FromEvent(messageReceiver);
}
这篇关于如何返回等待调度程序线程中的事件的等待(任务?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!