如何写一个“等待"方法? [英] How to write an "awaitable" method?

查看:28
本文介绍了如何写一个“等待"方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于开始研究 async &await 关键字,我有点像get",但是我见过的所有示例都调用了 .Net 框架中的异步方法,例如这个,它调用了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"程序.方法.是否像将要异步运行的代码封装在 Task 中并返回它一样简单?

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());

使其成为可等待的方法:

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();
}

请注意,这里的方法签名表示 async,因为该方法可能会将控制权返回给调用者,直到 ExpensiveTaskAsync() 返回.此外,在这种情况下,昂贵意味着耗时,例如 Web 请求或类似请求.要将繁重的计算发送到另一个线程,通常最好使用旧"方法,即用于 GUI 应用程序的 System.ComponentModel.BackgroundWorkerSystem.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.

这篇关于如何写一个“等待"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆