【问题标题】:How do I create multiple tasks in parallel using the Taskfactory Class? [duplicate]如何使用 Taskfactory 类并行创建多个任务? [复制]
【发布时间】:2014-12-13 06:53:52
【问题描述】:

我正在尝试使用 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);    
}

【问题讨论】:

  • 下次请记得添加适当的语言标签。我已经为你添加了 C# 标签。
  • 谢谢。非常感谢。
  • 使用信号量是将最大任务数限制为 5 个的更好方法。

标签: c# multithreading task taskfactory


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多