C # async waiting for Task.delay in action

I am having problems with the asynchronous delay task. I am writing an application that should run on a scale of tens / hundreds of thousands of asynchronously executed scripts. I do this using C # actions, and sometimes, during the execution of a certain sequence, for the script to execute correctly, it needs to wait until the external resource reaches the expected state. At first I wrote this with Thread.Sleep (), but it turned out to be a torpedo in application performance, so I'm looking for an asynchronous / waiting asynchronous sleep. But I can’t make him really wait for a pause! Can someone explain this?

static void Main(string[] args) { var sync = new List<Action>(); var async = new List<Action>(); var syncStopWatch = new Stopwatch(); sync.Add(syncStopWatch.Start); sync.Add(() => Thread.Sleep(1000)); sync.Add(syncStopWatch.Stop); sync.Add(() => Console.Write("Sync:\t" + syncStopWatch.ElapsedMilliseconds + "\n")); var asyncStopWatch = new Stopwatch(); sync.Add(asyncStopWatch.Start); sync.Add(async () => await Task.Delay(1000)); sync.Add(asyncStopWatch.Stop); sync.Add(() => Console.Write("Async:\t" + asyncStopWatch.ElapsedMilliseconds + "\n")); foreach (Action a in sync) { a.Invoke(); } foreach (Action a in async) { a.Invoke(); } } 

Execution Results:

Sync: 999

Async: 2

How to make it wait asynchronously?

+4
source share
1 answer

You have a problem with async void . When you pass async lambda to Action , the compiler creates an async void method for you.

As a best practice, you should avoid async void .

One way to do this is to have your list of actions List<Func<Task>> instead of List<Action> . This allows you to queue async Task methods instead of async void methods.

This means that your execution code will have to wait for each Task as it completes. In addition, your synchronous methods will need to return Task.FromResult(0) or something similar to match the Func<Task> signature.

If you want to use a larger solution, I recommend that you carefully consider the TPL data stream instead of creating your own queue.

+7
source

Source: https://habr.com/ru/post/1490547/


All Articles