转换动作< T>回调等待

编程入门 行业动态 更新时间:2024-10-28 08:25:41
本文介绍了转换动作< 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;回调等待

本文发布于:2023-11-07 07:00:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565831.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   动作   lt   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!