基于回调异步方法转换为awaitable任务的最佳方式 [英] Best way to convert callback-based async method to awaitable task
问题描述
什么是转换的最佳方式/包装经典异步使用回调的东西,返回(awaitable)任务的方法?
What would be the best way to convert/wrap a "classic" asynchronous method that uses a callback to something that returns a (awaitable) Task?
例如,考虑以下方法:
public void GetStringFromUrl(string url, Action<string> onCompleted);
我知道要包装成返回任务的方法这个问题的唯一办法是:
The only way I know of to wrap this into a method returning a task is:
public Task<string> GetStringFromUrl(string url)
{
var t = new TaskCompletionSource<string>();
GetStringFromUrl(url, s => t.TrySetResult(s));
return t.Task;
}
这是做到这一点的唯一途径?
Is this the only way to accomplish this?
和有没有办法来包装任务本身的调用GetStringFromUrl(URL,回调)(即调用本身将任务,而不是同步内运行)
And is there a way to wrap the call to GetStringFromUrl(url,callback) in the task itself (i.e. the call itself would run inside the task instead of synchronously)
推荐答案
您code是短的,可读的,高效的,所以我不明白你为什么要寻找替代品,但我想不出什么。我觉得你的做法是合理的。
Your code is short, readable and efficient, so I don't understand why are you looking for alternatives, but I can't think of anything. I think your approach is reasonable.
我也不清楚为什么你认为同步部分是原来的版本不错,但要避免它在工作
为主的之一。如果你想同步某些部分可能要花很长时间,解决它的方法的两个版本。
I'm also not sure why do you think that the synchronous part is okay in the original version, but you want to avoid it in the Task
-based one. If you think the synchronous part might take too long, fix it for both versions of the method.
但是,如果你希望异步运行(即在线程池
)仅在工作
的版本,你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/hh194918%28v=vs.110%29\"><$c$c>Task.Run()$c$c>:
But if you want to run it asynchronously (i.e. on the ThreadPool
) only in the Task
version, you can use Task.Run()
:
public Task<string> GetStringFromUrl(string url)
{
return Task.Run(() =>
{
var t = new TaskCompletionSource<string>();
GetStringFromUrl(url, s => t.TrySetResult(s));
return t.Task;
});
}
这篇关于基于回调异步方法转换为awaitable任务的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!