且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步调用库函数的相互依托,如何处理?

更新时间:2023-11-13 15:34:28

异步不(一定)是指平行的。

Async doesn't (necessarily) means parallel.

您可以拨打这两个异步方法的依序没有它们并行运行。简单地调用第一和的await 返回的任务,然后做同样的第二位。

You can call both async method sequentially without them running in parallel. Simply call the first and await the returned task and then do the same with the second.

var template = await TemplateInfo(...);
var message = //use template to create message
var sendResponse = await SendMessageTemplate(message);

这是仍然有用相比,同步code,因为同时异步操作跑有没有需要螺纹等你的线程可以在您的应用程序的其他部分去工作。

This is still useful compared to synchronous code because while the asynchronous operation is "running" there's no thread needed and so your threads can go work on other parts of your application.

如果您将调用都才把等待返回的任务并行,你会(可能)运行:

If you would call both and only then await the returned tasks you will (maybe) run in parallel:

var templateTask = TemplateInfo(...);
var sendResponseTask = SendMessageTemplate(message);
await templateTask;
await sendResponseTask;