转换动作< T>回调等待 [英] Convert Action<T> callback to an await

查看:70
本文介绍了转换动作< T>回调等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用 Action< String> 的方法。方法完成处理后,将使用返回值调用 Action< String>

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);
});

我想在web.api异步控制器中使用它。如何包装此方法,以便可以 await async 的方式完成此方法。我不能修改该方法本身,它是在旧版代码库中。

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.

我想做的就是这个

String returnValue = await MyWrapperMethodThatCallsMethodWithCallback();


推荐答案

您可以利用 TaskCompletionSource 类,并以通用方式解决该问题:

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;
}

这样,您不必修改 MethodWhitCallback

var result = await AsAsync<string>(MethodWithCallback);
Console.WriteLine(result);

这篇关于转换动作&lt; T&gt;回调等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆