多BackgroundWorker的排队 [英] multiple backgroundworker queueing

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

问题描述

在我的WinForms应用程序,我有一个包含对象队列:

in my winforms app, I have a Queue which contains objects:

    Queue<MyObj> _queuedRows = new Queue<MyObj>();

对于每一个对象,我必须启动一个单独的BackgroundWorker的做一些费时的工作。

For each object, I must start a separate backgroundworker to do some timeconsuming job.

    private void DoAll(List<MyObj> lst)
    {
        foreach (MyObj o in lst)
        {
            _queuedRows.Enqueue(o);
        }

        while (_queuedRows.Any())
            DoSingle();
    }

    private void DoSingle()
    {
        if (!isCancelPending())
        {
            if (_queuedRows.Any())
            {
                MyObj currentObj = _queuedRows.Dequeue();
                InitBackgroundWorker(currentObj);
            }
        }
    }

    private void InitBackgroundWorker(MyObj currentObj)
    {
        BackgroundWorker _worker = new BackgroundWorker();
        _worker.WorkerSupportsCancellation = true;
        _worker.WorkerReportsProgress = true;
        _worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

        if (!_worker.IsBusy && currentObj != null)
            _worker.RunWorkerAsync(currentObj);
    }

我的问题是,在调用的RunWorkerAsync之后,执行跳转到同时的下一次迭代(这是符合逻辑的,因为工人正在运行异步并且它允许为下一次迭代的情况发生)。

My problem is, after the call to RunWorkerAsync, the execution jumps to the next iteration of the while (which is logical, as the worker is running async and it allows for the next iteration to happen).

我真正需要做的,就是告诉应用程序莫名其妙地等待,直到BackgroundWorker的完成工作,然后才应该把它与调用DoSingle继续开始下一次迭代()。

What I actually need to do, is to tell the app somehow to WAIT until the backgroundworker has completed the job, and only then should it start the next iteration by continuing with calling DoSingle().

我应该适用于_queuedRows锁定对象或类似的东西?谢谢,

Should I apply a lock on the _queuedRows object or something similar? Thanks,

推荐答案

,将其更改为调用 DoSingle 一次,然后在后台工作的 RunWorkerCompleted 事件处理函数调用 DoSingle 一遍又一遍,直到队列完成。

Instead of calling DoSingle in the while loop, change it to call DoSingle once and then in the background worker's RunWorkerCompleted event handler call DoSingle again and again until the queue is done.

    private void DoAll(List<MyObj> lst)
    {
        foreach (MyObj o in lst)
        {
            _queuedRows.Enqueue(o);
        }

        if (_queuedRows.Any())
            DoSingle();
    }

此外,由于你不是在并行处理队列中的所有对象,实例化背景工人只有一次,重复使用。

Also since you're not processing all objects in the queue in parallel, instantiate background worker only once and reuse it.

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

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