如何将await异步函数转换为将回调作为参数的函数?

编程入门 行业动态 更新时间:2024-10-18 06:01:49
本文介绍了如何将await异步函数转换为将回调作为参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Hi 我需要在一个等待的异步版本和一个以回调函数作为参数的版本中拥有自己的C#函数,并且可以从多个线程调用同一时间。回调版本必须基于异步版本。 我的等待功能是: 公共异步任务< MyClass的> GetDocumentAsync(长身份证) { //我已经拥有此功能。 } GetDocumentAsync(...)必须变成 public void GetDocumentWithCallback(Action< MyClass> callback,long ID) { // 1。可以同时从多个线程调用。 // 2。必须是无阻塞的。 // 3。必须基于对等待版本的调用GetDocumentAsync(...) //请帮我写这个函数?? } 我希望有人可以帮我写作GetDocumentWithCallback(...)

Hi I need to have my own C# function in both an awaitable async version and in a version that takes a callback function as a parameter and can be called from multiple threads at the same time. The callback version must be based on the async version. My awaitable function is: public async Task<MyClass> GetDocumentAsync(long ID) { //I already have this function. } GetDocumentAsync(...) must be turned into public void GetDocumentWithCallback(Action<MyClass> callback, long ID) { //1. Can be called from multiple threads at the same time. //2. Must be none-blocking. //3. Must be based on a call to the awaitable version GetDocumentAsync(...) //Please help me with writing this function?? } I hope someone can help my writing GetDocumentWithCallback(...)

推荐答案

这样的事情怎么样: How about something like this: public void GetDocumentWithCallback(Action<MyClass> callback, long ID) { Task<MyClass> task = GetDocumentAsync(ID); task.ContinueWith(t => callback(t.Result)); }

注意:与 async 版本不同, callback 将不会在与调用者相同的上下文中执行。这意味着您将无法访问Windows窗体/ WPF应用程序中的UI,并且不会在ASP.NET应用程序中设置 HttpContext.Current 。 /> 如果这是一个问题,你必须明确捕获并恢复上下文:

NB: Unlike the async version, callback will not be executed in the same context as the caller. That means you won't be able to access the UI in a Windows Forms / WPF application, and HttpContext.Current will not be set in an ASP.NET application. If that's a problem, you'll have to explicitly capture and restore the context:

public void GetDocumentWithCallback(Action<MyClass> callback, long ID) { Task<MyClass> task = GetDocumentAsync(ID); ExecutionContext context = ExecutionContext.Capture(); ContextCallback contextCallback = state => callback((MyClass)state); task.ContinueWith(t => ExecutionContext.Run(context, contextCallback, t.Result)); }

更多推荐

如何将await异步函数转换为将回调作为参数的函数?

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

发布评论

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

>www.elefans.com

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