如果我不在乎它的返回值,是否应该等待“异步任务"功能? [英] Should I await a 'async Task' function if I don't care its return value?

查看:95
本文介绍了如果我不在乎它的返回值,是否应该等待“异步任务"功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不返回任何内容,我是否需要等待异步Task函数?会导致以下代码包装在委托中并在异步Task函数返回后执行吗?

Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}

在上面的示例中,如果我在Test()中等待DoSomethingAsync(),是否会导致以下代码Console.WriteLine被包装在委托中并仅在异步任务完成后才执行?

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?

推荐答案

如果不返回任何内容,我是否需要等待异步Task函数?

Do I need to await a async Task function if it doesn't return anything?

通常,是的.这样不仅可以检测完成时间,还可以响应任何错误.如果需要,可以存储Task对象,以后再存储await.

Generally, yes. Not only does this allow you to detect when it completes, it also allows you to respond to any errors. You can, if you wish, store the Task object and await it later.

不是等待任务的是即发即弃",字面意思是:

Not awaiting the task is "fire and forget", which literally means:

  • 您不在乎它是否完成.
  • 您不在乎它何时完成.
  • 您不在乎它是成功还是失败.

拥有真正的一劳永逸"场景的情况很少见.

It's very rare to have a true fire-and-forget scenario.

是否将导致以下代码包装在委托中并在异步Task函数返回后执行?

Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

异步函数返回的Task完成后,是的.

After the Task returned by the async function completes, yes.

这篇关于如果我不在乎它的返回值,是否应该等待“异步任务"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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