Asynchronous method does not work in parallel

The following code in method B uses the code Trace.TraceInformation ("B - Started"); never called.

Should the method work in parallel?

using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        private static async Task A()
        {
            for (;;)
            {
            }
        }


        private static async Task B()
        {
            Trace.TraceInformation("B - Started");
        }

        static void Main(string[] args)
        {
            var tasks = new List<Task> { A(), B() };
            Task.WaitAll(tasks.ToArray());
        }
    }
}
+4
source share
3 answers

Short answer

No, since you wrote your two methods async, they really don't work in parallel. Adding await Task.Yield();to your first method (for example, inside a loop) will allow them to do this, but there are more reasonable and simple methods that are very dependent on what you really need (alternate execution on one thread? Actual parallel execution on several topics?).

Long answer

, async - . , - : Async Await

A , await. await , .

, await , , , .

, Task.Run .

await Task.Yield() , null, , ( ThreadPoolTaskScheduler) - , , .

: :

  • concurrency ( async/await )
  • parallelism ( , , Task.Run, Thread .., async )
+9

async magicwnwn-a-thread-here. - , ( , -...), , .

A , Task.Run, , . , await - , A : await Task, , , Task. await -ing Task.Run(A) , A, ( ).

, , -, . -, ( - Task.FromResult), , . , .

+2

, " ".

B - tasks, .Add - A(). A await, . B().

A ( ), B.

, , WaitAll, A .

If you want the methods to be executed in parallel, you need to either run them implicitly / explicitly in new threads (i.e. using Task.Runor Thread.Start), or for related I / O calls. Allows a method to release a stream with await.

+1
source

All Articles