如何使用任务工厂类并行创建多个任务
本文关键字:任务 创建 并行 何使用 工厂 | 更新日期: 2023-09-27 18:34:08
我正在尝试使用 TaskFactory 类并行创建多个任务,每个任务一个挂起正在处理的事务 ID,最多 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);
}
假设您要创建 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);
}