Async method not running in parallel

前端 未结 3 1241
忘了有多久
忘了有多久 2020-12-11 09:09

In the following code, in the B method, the code Trace.TraceInformation(\"B - Started\"); never gets called.

Should the method be running in parallel?



        
3条回答
  •  悲哀的现实
    2020-12-11 09:21

    No, the methods shown are not expected to "run in parallel".

    Why B is never called - you have list of tasks tasks constructed via essentially series of .Add calls - and first is result of A() is added. Since the A method does not have any await it will run to the completion synchronously on the same thread. And after that B() would be called.

    Now A will never complete (it is sitting in infinite loop) so really code will not even reach call to B.

    Note that even if creation would succeed code never finish WaitAll as A still sits in infinite loop.

    If you want methods to "run in parallel" you need to either run them implicitly/explicitly on new threads (i.e. with Task.Run or Thread.Start) or for I/O bound calls let method to release thread with await.

提交回复
热议问题