次のような方法があります。
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
が、コードビハインドが明らかに奇妙に見えたので、信用できませんでした。誰でもこれを行う方法を考えることができますか?