获取当前任务实例在异步方法体实例、任务、方法

2023-09-05 00:06:22 作者:寻找爱 Looking

如果我有一个异步方法的身体像这样 -

If I have an async method body like so -

public async Task GetSomething() {

    await SendText("hi");
    await SendImage("bla.bmp");

}

我怎样才能获得工作的对象,然后才返回时,等待踢

How can I get the Task object before it is returned to the user when the await kicks in

如..

public async Task GetSomething() {

    myTasks.Add(Task.Current);
    await SendText("hi");
    await SendImage("bla.bmp");

    //some processing

}

让别的地方我可以做

so that somewhere else I can do

 await Task.WhenAll(myTasks);
 Console.WriteLine("All tasks complete");

这是为了让我可以等所有任务关闭前

This is so that I can wait for all tasks to complete before shutting down

推荐答案

这是不能直接作为语言没有一个机构来访问当前的任务。

This is not directly possible as the language does not have a facility to access the "current" task.

有一种变通方法,但:在另一种方法包装你的异步方法。这的等的方法可以掌握,一旦异步方法返回的任务(这在第一计谋点发生约)的。

There is a workaround though: Wrap your async method in another method. This other method can get hold of the task once the async method returns (which happens approximately at the first await point).

在所有情况下,我建议让呼叫者加入异步任务到您的列表,而不是异步方法本身。此即使从视图封装点是有用的。

In all cases I recommend letting the caller add the async Task to your list, not the async method itself. This is useful even from an encapsulation point of view.