How to run multiple tasks in C #?

How to change the following code and perform multiple tasks at the same time?

foreach (SyndicationItem item in CurrentFeed.Items) { if (m_bDownloadInterrupted) break; await Task.Run( async () => { // do some downloading and processing work here await DoSomethingAsync(); } } 

I also need to take a break and stop the process. Because my DoSomethingAsync method reads a tag (global boolean) to stop the process.

thanks

+4
source share
2 answers

This will process the elements at the same time.

  Parallel.ForEach(CurrentFeed.Items, DoSomethingAsync) 

To be able to cancel, you may need a CancellationToken.

  CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions po = new ParallelOptions(); po.CancellationToken = cts.Token; // Add the ParallelOptions with the token to the ForEach call Parallel.ForEach(CurrentFeed.Items,po ,DoSomethingAsync) // set cancel on the token somewhere in the workers to make the loop stop cts.Cancel(); 

For more details see (among other sources) http://msdn.microsoft.com/en-us/library/ee256691.aspx

+1
source

No, this will not launch them at the same time - you are waiting for each of them to complete before the next one begins.

You can put the results of each call to Task.Run in a collection, and then wait for Task.WhenAll after they start.

(Too bad Parallel.ForEach does not return the Task you might expect. There may be a more asynchronous version around ...)

+9
source

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


All Articles