如何将await异步函数转换为将回调作为参数的函数? [英] How to convert an await async function to a function that takes a callback as parameter?
问题描述
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异步函数转换为将回调作为参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!