I have a method that goes like this:
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;
}
For my API, though, I need to offer a synchronous alternative. Therefore, I would need an object that can wait until signalled, but can carry an object. AutoResetEvent almost meets my criteria, and this is what I've got so far:
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?
}
However, I need to get the result. I can't see of a way to do this. I thought of making an EventWaitHandle
derivative, but the codebehind looked distinctly odd, so I couldn't trust it. Can anyone think of a way to do this?
You can simply declare a local variable, set it in the callback, then return it.