How do I create multiple tasks in parallel using the Taskfactory Class?

2.4k Views Asked by At

I am attempting to use the TaskFactory Class to create multiple task in parallel, one for each pending transactionId that is being processed, up to a max of 5 threads. I need to pass each task the cancelation token. Am I on the right track? How do i get it to run async vs running sync? I have the following:

public int ProcessPendingTransactions()
{

    //set the max # of threads
    ThreadPool.SetMaxThreads(5, 5);

    //create an action
    //The Run method is what i am trying to create multiple tasks in parallel on
    Action action = delegate() { abc.Run(transactionId); };

    //kick off a new thread async
    tfact.StartNew(action, MyCTkn, TaskCreationOptions.None, (TaskScheduler)null);    
}
1

There are 1 best solutions below

0
On

Suppose, you want to create 200 actions each taking 1 second to complete(DoSomething), and want to run them in parallel with 25 threads. Then, it should take about ~8 seconds (in theory).

async void MainMethod()
{
    var sw = Stopwatch.StartNew();

    //Create Actions
    var actions = Enumerable.Range(0,200)
                            .Select( i=> ((Action)(()=>DoSomething(i))));

    //Run all parallel with 25 Tasks-in-parallel
    await DoAll(actions, 25);

    Console.WriteLine("Total Time: " + sw.ElapsedMilliseconds);
}


void DoSomething(int i)
{
    Thread.Sleep(1000);
    Console.WriteLine(i + " completed");
}

async Task DoAll(IEnumerable<Action> actions, int maxTasks)
{
    SemaphoreSlim semaphore = new SemaphoreSlim(maxTasks);

    foreach(var action in actions)
    {
        await semaphore.WaitAsync().ConfigureAwait(false);
        Task.Factory.StartNew(() =>action(), TaskCreationOptions.LongRunning)
                    .ContinueWith((task) => semaphore.Release());
    }

    for (int i = 0; i < maxTasks; i++)
        await semaphore.WaitAsync().ConfigureAwait(false);
}