I'm using the async/await pattern throughout my code. However, there's one API which used the event-based asyncronous pattern. I've read on MSDN, and several StackOverflow answers, that the way to do this is to use a TaskCompletionSource.
My code:
public static Task<string> Process(Stream data)
{
var client = new ServiceClient();
var tcs = new TaskCompletionSource<string>();
client.OnResult += (sender, e) =>
{
tcs.SetResult(e.Result);
};
client.OnError += (sender, e) =>
{
tcs.SetException(new Exception(e.ErrorMessage));
};
client.Send(data);
return tcs.Task;
}
And called as:
string result = await Process(data);
Or, for testing:
string result = Process(data).Result;
The method always returns very quickly, but neither of the events get triggered.
If I add tcs.Task.Await(); just before the return statement, it works, but this doesn't provide the asyncronous behavior I want.
I've compared with the various samples I've seen around the internet, but don't see any difference.