C# 如何使用Taskfactory类并行创建多个任务?
我试图使用TaskFactory类并行创建多个任务,每个任务对应一个挂起的任务 正在处理的transactionId,最多5个线程。我需要向每个任务传递取消令牌。我走对了吗?如何让它运行异步与运行同步? 我有以下资料:C# 如何使用Taskfactory类并行创建多个任务?,c#,multithreading,task,taskfactory,C#,Multithreading,Task,Taskfactory,我试图使用TaskFactory类并行创建多个任务,每个任务对应一个挂起的任务 正在处理的transactionId,最多5个线程。我需要向每个任务传递取消令牌。我走对了吗?如何让它运行异步与运行同步? 我有以下资料: public int ProcessPendingTransactions() { //set the max # of threads ThreadPool.SetMaxThreads(5, 5); //create an action //
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 main方法()
{
var sw=Stopwatch.StartNew();
//创建操作
变量操作=可枚举范围(0200)
.选择(i=>((动作)(()=>DoSomething(i)));
//并行运行所有任务,并行运行25个任务
等待道尔(行动,25);
Console.WriteLine(“总时间:+sw.ElapsedMilliseconds”);
}
无效剂量测定(int i)
{
睡眠(1000);
控制台写入线(i+“已完成”);
}
异步任务DoAll(IEnumerable操作,int-maxTasks)
{
信号量slim信号量=新信号量slim(maxTasks);
foreach(行动中的var行动)
{
wait semaphore.WaitAsync().ConfigureWait(false);
Task.Factory.StartNew(()=>action(),TaskCreationOptions.LongRunning)
.ContinueWith((task)=>semaphore.Release());
}
对于(int i=0;i
下次请记住添加适当的语言标记。我为您添加了C#标记。谢谢。我很感激。使用信号灯是将最大任务数限制为5个的更好方法。
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);
}