问题
I have a method that takes a Action<String>
. When the method finishes its processing it calls the Action<String>
with the return value.
MethodWithCallback((finalResponse)=> {
Console.WriteLine(finalResponse);
});
I want to use this in a web.api async controller. How do I wrap this method so I can await
for this method to complete in an async
manner. I cannot modify the method itself, it is in a legacy code base.
What I would like to be able to do is this
String returnValue = await MyWrapperMethodThatCallsMethodWithCallback();
回答1:
You can leverage the TaskCompletionSource class and solve the problem in a generic way:
Task<T> AsAsync<T>(Action<Action<T>> target) {
var tcs = new TaskCompletionSource<T>();
try {
target(t => tcs.SetResult(t));
} catch (Exception ex) {
tcs.SetException(ex);
}
return tcs.Task;
}
That way you don't have to modify your MethodWhitCallback
:
var result = await AsAsync<string>(MethodWithCallback);
Console.WriteLine(result);
来源:https://stackoverflow.com/questions/16830601/convert-actiont-callback-to-an-await