Task status changes to RanToCompletion if the Task await's something

后端 未结 2 1839
清酒与你
清酒与你 2020-12-14 18:48

The question describes the same problem found here - MSDN Developer Forum. The question does not have an accepted answer, neither any of the answers given can be applied to

2条回答
  •  旧时难觅i
    2020-12-14 19:16

    There are two things wrong: async void and Task.Factory.StartNew. Both of these are bad practices.

    First, async void does not allow the calling code to know when it completes. So it doesn't matter that you're waiting; the async void method will return fairly quickly, and your app can't know when Accept actually finishes. To fix this, replace async void with the much more proper async Task.

    Second, StartNew doesn't understand asynchronous delegates. StartNew is an extremely low-level API that should not be used in 99.99% of production code. Use Task.Run instead.

    public static async Task Accept(object state);
    
    Task t1 = Task.Run(() => Accept(s1));
    Task t2 = Task.Run(() => Accept(s1));
    Task.WaitAll(t1, t2);
    

提交回复
热议问题