用于执行的队列多线程方法 [英] Queue Multithreaded Methods for Execution
问题描述
所有,我有一个名为 TaskSpin
的通用方法,在这个方法中我启动了一个 Task
与关联的 continuation
All, I have a generic method called TaskSpin
, in this method I launch a Task
with an ascociated 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
运行多个方法,但我需要限制这些方法一次运行一个.所以在某些 DataGridView
中的 foreach 行我想做一些像
The problem is now that I want to run multiple methods using TaskSpin
, but I need to restrict the methods to run one-at-a-time. So foreach row in some DataGridView
I want to do something like
foreach (DataGridViewRow row in this.DataGridViewUrg.Rows)
TaskSpin(Run(DrgDataRowInfo(row.Index)));
然而,在上面的 TaskSpin
方法将立即退出,导致 TaskSpin
在另一个线程上分离下一个方法.这并不好,因为 Run
方法写入一组公共文件.将这些作业排队的最佳方法是什么?
However, in the above the TaskSpin
method will exit immediately causing TaskSpin
to spin off the next method on yet another thread. This is no good as the Run
method write to a common set of files. What is the best way to queue these jobs?
推荐答案
您可以实现自己的任务队列,并在每个任务完成后继续处理队列,直到队列为空,例如
You could implement your own task queue and just keep processing the queue after each task is complete until it's empty e.g.
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();
}
...
}
这篇关于用于执行的队列多线程方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!