C# TaskCompletionSource的同步等价物是什么<;T>;?
我有一个方法是这样的:C# TaskCompletionSource的同步等价物是什么<;T>;?,c#,event-handling,task,taskcompletionsource,C#,Event Handling,Task,Taskcompletionsource,我有一个方法是这样的: Task<MyClass> MyMethodAsync() { SendBluetoothMessageAsync(); var tcs = new TaskCompletionSource<MyClass>(); Bluetooth.MessageRecieved += (o, e) => tcs.SetResult(e.SomeProperty); //this removes itself afterwa
Task<MyClass> MyMethodAsync()
{
SendBluetoothMessageAsync();
var tcs = new TaskCompletionSource<MyClass>();
Bluetooth.MessageRecieved += (o, e) => tcs.SetResult(e.SomeProperty);
//this removes itself afterwards, but boilerplate removed
return await tcs.Task;
}
然而,我需要得到结果。我看不出有什么办法可以做到这一点。我想做一个
EventWaitHandle
派生,但是代码隐藏看起来很奇怪,所以我不能相信它。有人能想出一种方法吗?你可以简单地声明一个局部变量,在回调中设置它,然后返回它。我真傻。谢谢
MyClass MyMethodAsync()
{
SendBluetoothMessage();
var are = new AutoResetEvent();
Bluetooth.MessageRecieved += (o, e) => are.Set(); //removes itself too
return null; //problem: how do I get the result?
}