队列执行Mutithreaded方法 [英] Queue Mutithreaded Methods for Execution

查看:123
本文介绍了队列执行Mutithreaded方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有的,我有一个叫泛型方法 TaskSpin ,在这个方法我发动工作与ascociated continutation

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 ,但我需要限制的方法来运行一个-AT-A-时间。在某些那么的foreach行 DataGridView的我想要做的事,比如

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 分拆下一个方法上的另一个线程。这是没有好作为运行方法写一组共同文件。什么是排队这些职位的最佳方法是什么?

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();           
    }  
    ...                 
}

这篇关于队列执行Mutithreaded方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆