如何使用Taskfactory类并行创建多个任务?

时间:2014-12-12 20:32:15

标签: c# multithreading task taskfactory

我正在尝试使用TaskFactory类并行创建多个任务,每个任务对应一个 正在处理的transactionId,最多5个线程。我需要将每个任务传递给取消令牌。我是在正确的轨道上吗?如何让它运行异步与运行同步? 我有以下内容:

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 个答案:

答案 0 :(得分:1)

假设您要创建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);
}