简体   繁体   English

C# 异步函数 - 一起使用 WhenAll 函数和 await word

[英]C# Async function - using WhenAll function and await word together

I need to understand something, i have a function, for example:我需要了解一些东西,我有一个功能,例如:

public static class classExample
{
     public async Task funcAsync()
    {

        List<Task<string>> exampleList= new List<Task<string>>();
        // do stuff          
        await Task.WhenAll(exampleList);
    }
}

and in my main method i have:在我的主要方法中,我有:

 main()
 {
       classExample.funcAsync();         
 }

If i use await word in main like this:如果我像这样在 main 中使用 await 字:

await classExample.funcAsync();

is different from without await in main?和 main 中没有 await 有什么不同? i asking because i have我问是因为我有

await Task.WhenAll(exampleList);

inside the function.函数内部。

What the different?有什么不同?

And more question, i have this example:还有更多问题,我有这个例子:

async Task function2()
{
    // do stuff
    await //for some code will be done
}

main()
{
    function2();
    function3();
}

If i not use await word so the function will continue to function3, in this case i not need that function3 waiting to function2 and this is can to continue but the question: will the function2 do all the work?如果我不使用 await 字,那么函数将继续执行函数 3,在这种情况下,我不需要函数 3 等待函数 2,这可以继续,但问题是:函数 2 会完成所有工作吗? in case function3 will end all the work before function2 will end.如果 function3 将在 function2 结束之前结束所有工作。 after function3 will end all the work the main function wait to function2 will ended?在function3将结束所有工作之后,main函数等待function2将结束?

Thanks!谢谢!

If I use await word in main like this: await classExample.funcAsync();如果我像这样在 main 中使用 await 字: await classExample.funcAsync(); is different from without await in main?和 main 中没有 await 有什么不同?

Yes, funcAsync returns a Task which will complete when all the exampleList Task s have completed (due to the use of Task.WhenAll ), so without using await , your Main will likely exit before those have all completed.是的, funcAsync返回Task时,所有这些将完成exampleList Task ■找完成(由于使用的Task.WhenAll ),所以不使用await ,您Main将那些以前可能退出已全部完成。

In your second example, not awaiting function2 will allow function3 to execute without waiting for function2 to complete, however, if function3 completes before the Task returned from function2 has completed, then your code will exit prematurely.在您的第二个示例中,不等待function2将允许function3在不等待function2完成的情况下执行,但是,如果function3在从function2返回的Task完成之前完成,那么您的代码将过早退出。

You can mitigate this by storing a reference to the Task and awaiting later:您可以通过存储对Task的引用并稍后等待来缓解这种情况:

var task = function2();
function3();
await task;

Or if function3 also returns a Task :或者如果function3也返回一个Task

await Task.WhenAll(function2(), function3());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM