简体   繁体   中英

How to call same method n times using tasks to run in parallel in c#?

I want to call method which does time consuming job from different threads.

Public void DoSomeWork(int n)
{
  // Time Consuming operation depending on n. 
}

1 - I am trying to use task instead of thread & threadpool.
2 - There should be at max n threads running in parallel
3 - While I tried to use 'SemaphoreSlim' I found it's calling same thread calling method multiple times and run into unhanded exception.

Implementation:

 for (int i = 0; i < SomeNumberList.Count; i++)
        {
            semaphore.Wait();
            Task.Factory.StartNew(() => DoSomeWork(SomeNumberList[i])).ContinueWith(x => semaphore.Release());
        }

How to use task to call DoSomeWork by concurrent threads using task and how to do error handling for it?

Parallel.For already gives you the necessary marshalling for this sort of task.

    const int n = 5; // No more than "n threads"
    Parallel.For(0,  SomeNumberList.Count, new ParallelOptions{MaxDegreeOfParallelism = n}, i =>
    {
        DoSomeWork(i);
    }

There is another overload which gives you ParallelLoopState if you need to handle exceptions or break calls based on what is happening in concurrent executions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM