如何写" awaitable"方法? [英] How to write an "awaitable" method?
问题描述
我终于寻找到异步和放大器;等待的关键字,我有种搞定,但所有的例子我见过的.NET Framework中,例如,呼叫异步方法这一,这就要求 HttpClient.GetStringAsync()
。
I'm finally looking into the async & await keywords, which I kind of "get", but all the examples I've seen call async methods in the .Net framework, e.g. this one, which calls HttpClient.GetStringAsync()
.
什么我不是很清楚就是在这样的方法的推移,我会怎么写我自己的awaitable的方法。它是那样简单包裹code,我想在一个任务异步运行,并返回?
What I'm not so clear on is what goes on in such a method, and how I would write my own "awaitable" method. Is it as simple as wrapping the code that I want to run asynchronously in a Task and returning that?
推荐答案
这是因为
Task.Run(() => ExpensiveTask());
要使它成为一个awaitable方式:
To make it an awaitable method:
public Task ExpensiveTaskAsync()
{
return Task.Run(() => ExpensiveTask());
}
这里最重要的是返回的任务。该方法甚至没有被异步标记。 (刚看了一点点进一步为它进入图片)
The important thing here is to return a task. The method doesn't even have to be marked async. (Just read a little bit further for it to come into the picture)
现在这可以被称为
async public void DoStuff()
{
PrepareExpensiveTask();
await ExpensiveTaskAsync();
UseResultsOfExpensiveTask();
}
请注意,这里的方法签名说异步
,因为该方法可以控制权返回给调用者,直到 ExpensiveTaskAsync()
回报。此外,在这种情况下,昂贵的装置,耗时,例如网络请求或类似。送过重计算到另一个线程,它通常是更好地使用旧的方法,即 System.ComponentModel.BackgroundWorker
的GUI应用程序或 System.Threading.Thread
。
Note that here the method signature says async
, since the method may return control to the caller until ExpensiveTaskAsync()
returns. Also, expensive in this case means time-consuming, like a web request or similar. To send off heavy computation to another thread, it is usually better to use the "old" approaches, i.e. System.ComponentModel.BackgroundWorker
for GUI applications or System.Threading.Thread
.
这篇关于如何写" awaitable"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!