C#异步/等待等待不等待 [英] C# async/await await doesn't await

查看:920
本文介绍了C#异步/等待等待不等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.Net 4.7.2和C#7

I am using .Net 4.7.2 and C# 7

在一个类中,有一些服务器方法,全部无效.其中一些可以异步执行,其他一些则必须顺序执行.因此,我为并联定义了一个列表

In a class there are serveral methods, all void. Some of them can be executed asynchronously, others have to be executed sequentially. So I defined a list for the parallels

private void ExecuteSequential()
{
    SomeMethod1();
    SomeMethod2();
    ExecuteParallelAsync();
    SomeMethod3();
    SomeMethod4();
}


private async void ExecuteParallelAsync()
{
    List<Action> methods = new List<Action>()
    {
        MyMethod1,
        MyMethod2,
        MyMethod3
    };


    await Task.Run( () => { Parallel.ForEach( methods , ( currentMethod ) => currentMethod.Invoke() ); } );            
}

SomeMethod3 恰好被执行之前, ExecuteParallelAsync 应该完全完成. 因为不是这种情况,所以我对async和await的使用显然有问题.

Before SomeMethod3 happens to be executed ExecuteParallelAsync should be finished entirely. Because that's not the case, apparently something is wrong with my usage of async and await.

我做错了什么?

提前谢谢!

推荐答案

async void-所有投注均已取消;实际上,除非您处在需要它们的极端极端情况的微小组中,否则您应该从不编写async void方法,例如异步事件处理程序.

async void - all bets are off; in reality, you should never write an async void method unless you're in the tiny tiny set of extreme corner cases that require it, such as async event-handlers.

在执行SomeMethod3之前,ExecuteParallelAsync应该完全完成.

Before SomeMethod3 happens to be executed ExecuteParallelAsync should be finished entirely.

它怎么可能知道? :async void,这意味着它没有给显示状态的呼叫者任何东西 em>.

how could it possibly know? it is: async void, which means it doesn't give anything to the caller that indicates the state.

这样做,必须 为:

private async Task ExecuteParallelAsync() // or ValueTask

必须在呼叫站点上等待

await ExecuteParallelAsync();

这篇关于C#异步/等待等待不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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