Convert Action<T> callback to an await

流过昼夜 提交于 2019-12-12 13:35:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!