0

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);    
}
4

1 回答 1

2

假设您要创建 200 个动作,每个动作需要 1 秒才能完成(DoSomething),并希望以 25 个线程并行运行它们。然后,它应该需要大约 8 秒(理论上)。

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);
}
于 2014-12-12T22:37:31.383 回答