gpt4 book ai didi

c# - 用于执行的队列多线程方法

转载 作者:行者123 更新时间:2023-11-30 15:38:09 24 4
gpt4 key购买 nike

全部,我有一个名为 TaskSpin 的通用方法,在这个方法中我启动了一个 Task 和一个相关的 continutation

public TaskSpin(Func asyncMethod, object[] methodParameters)
{
...
asyncTask = Task.Factory.StartNew<bool>(() =>
asyncMethod(uiScheduler, methodParameters));

asyncTask.ContinueWith(task =>
{
// Finish the processing update UI etc.
}
...
}

现在的问题是我想使用 TaskSpin 运行多个方法,但我需要限制这些方法一次运行一个。所以 foreach 行在一些 DataGridView 我想做一些像

foreach (DataGridViewRow row in this.DataGridViewUrg.Rows)
TaskSpin(Run(DrgDataRowInfo(row.Index)));

但是,在上面的 TaskSpin 方法将立即退出导致 TaskSpin 在另一个线程上分拆下一个方法。这并不好,因为 Run 方法写入一组通用文件。排列这些作业的最佳方式是什么?

最佳答案

您可以实现自己的任务队列,并在每个任务完成后继续处理队列,直到它为空,例如

using TaskPair = KeyValuePair<Func, object[]>;
...

private Queue<TaskPair> taskQueue;
...

// generate the queue of tasks
this.taskQueue = new Queue<TaskPair>(this.DataGridViewUrg.Rows);
foreach (DataGridViewRow row in this.DataGridViewUrg.Rows)
{
var task = new TaskPair(Run(DrgDataRowInfo(row.Index)), /* params */);
this.taskQueue.Enqueue(task);
}
// initiate queue processing
ProcessNextTask();

....
private void ProcessNextTask()
{
try
{
var item = this.taskQueue.Dequeue();
TaskSpin(item.Key, item.Value);
}
catch(InvalidOperationException)
{
// queue is empty
}
}

....
// Execute task and process next in queue (if applicable)
public TaskSpin(Func asyncMethod, object[] methodParameters)
{
...
asyncTask = Task.Factory.StartNew<bool>(() =>
asyncMethod(uiScheduler, methodParameters));

asyncTask.ContinueWith(task =>
{
// Finish the processing update UI etc.
ProcessNextTask();
}
...
}

关于c# - 用于执行的队列多线程方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com