2013-10-15 40 views
0

我有一个是这样的方法:什么是TaskCompletionSource的同步等效物<T>?

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; 
} 

对于我的API,不过,我需要提供一个同步的选择。因此,我需要一个可以等待信号的对象,但可以携带一个对象。 AutoResetEvent几乎符合我的标准,这是我目前为止:

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? 
} 

但是,我需要得到结果。我看不到有办法做到这一点。我想制作一个EventWaitHandle派生物,但代码隐藏看起来很奇怪,所以我不能相信它。任何人都可以想办法做到这一点?

回答

1

你可以简单地声明一个局部变量,在回调中设置它,然后返回它。

+0

这对我来说很愚蠢。谢谢。 –

相关问题