简体   繁体   English

单个Windows Form C#中的多个BackGroundWorker组件

[英]Multiple BackGroundWorker components in a single Windows Form C#

Before discussing my problem, I want to know you about my stage.I am very new to C# programming. 在讨论我的问题之前,我想了解一下我的阶段。我对C#编程非常陌生。 It is the first time I am working on it. 这是我第一次进行这项工作。 So my knowledge in C# is very minimum. 因此,我对C#的了解非常少。

I am developing my application using Windows Forms in C#. 我正在使用C#中的Windows窗体开发我的应用程序。 At some instant I was supposed to run 5 operations simultaneously . 有时我应该同时执行5个操作。 So that I tried the BackGroundWorker Component in the ToolBox of C#. 因此,我尝试了C#工具箱中的BackGroundWorker组件。

But using that, I could process only one of my operations among 5. I tried using 5 BackGroundWorker Components from the ToolBox and defined the DoWork functions seperately. 但是使用它,我只能处理5个操作之一。我尝试使用工具箱中的5个BackGroundWorker组件,并分别定义DoWork函数。

But when I called the RunWorkerAsync() function it threw an error saying " backgroundworker is currently busy and cannot run multiple tasks concurrently ". 但是,当我调用RunWorkerAsync()函数时,它引发了一个错误,提示“ backgroundworker is currently busy and cannot run multiple tasks concurrently ”。

I don't whether I can use multiple BackGroundWorker in my program.Creating array didn't help me. 我不知道我是否可以在程序中使用多个BackGroundWorker 。创建数组对我没有帮助。 Because I have a infinite loop to be run inside the DoWork functions of the BackGroundWorker components. 因为我有一个无限循环要在BackGroundWorker组件的DoWork函数中运行。 If there is any other way to run 5 operations at the same time, Please help me get an idea about that. 如果还有其他方法可以同时执行5个操作,请帮助我了解一下。 Thanks in advance. 提前致谢。

Here is my code: 这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;


namespace myapp5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);

            bw1.WorkerSupportsCancellation = true;
            bw1.WorkerReportsProgress = true;

            bw1.DoWork += new DoWorkEventHandler(bw1_DoWork);
        }

        BackgroundWorker bw = new BackgroundWorker();
        BackgroundWorker bw1 = new BackgroundWorker();
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                try
                {
                    videostream();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }
        private void bw1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                try
                {
                    videostream();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {

            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
            else
            {
                MessageBox.Show("Background Worker is busy");
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
                bw.Dispose();
                MessageBox.Show("Background Closed");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (bw1.IsBusy != true)
            {
                bw1.RunWorkerAsync();
            }
            else
            {
                MessageBox.Show("Background Worker is busy");
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if (bw1.WorkerSupportsCancellation == true)
            {
                bw1.CancelAsync();
                bw1.Dispose();
                MessageBox.Show("Background Closed");
            }
        }
    }
}

If you want to perform 5 different function parallel than you need to 5 backgroundworker thread for that. 如果要并行执行5个不同的功能,而不是5个backgroundworker线程。 One Backgroupwork thread is not sufficient for running 5 different function parallel. 一个Backgroupwork线程不足以并行运行5个不同的功能。

You can also you TPL(taksparallel) library for this instead of backgroundworker. 您也可以为此使用TPL(taksparallel)库而不是backgroundworker。

You should try thread for nominal use. 您应该尝试名义使用螺纹。

private object threadUnsafeObject;
    private object locker = new object();

    private void RunMulitpleThread()
    {
        object pass_your_parameter_here = "";
        for (int iCount = 0; iCount < 5; iCount++)
        {
            System.Threading.Thread thread = new System.Threading.Thread(DoWork);
            thread.Start(pass_your_parameter_here);

        }
    }

    private void DoWork(object parameters)
    {
        lock (locker)
        {
            threadUnsafeObject = parameters;
        }
    }

I think that your program have logical error so the same BackgroundWorker instance is used five times for calling RunWorkerAsync(). 我认为您的程序有逻辑错误,因此同一BackgroundWorker实例被五次调用RunWorkerAsync()。 Review the code for this. 查看此代码。

UPD UPD

Your DoWork handler must look like this: 您的DoWork处理程序必须如下所示:

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    while (true)
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
            // perform work partially with short time!
            // and break the while loop at the end
        }
    }
}

UPD-2 UPD-2

Don't use Dispose() for workers. 不要为员工使用Dispose()。

If you're using .net 4.0 or above, you should use Tasks. 如果您使用的是.net 4.0或更高版本,则应使用“任务”。 This is the direction where the .NET framework is moving. 这就是.NET框架的发展方向。 I've set up two fiddles for you to check out. 我设置了两个小提琴供您结帐。 If you're using .NET 4.0 : https://dotnetfiddle.net/GUxD2j . 如果您使用的是.NET 4.0: https : //dotnetfiddle.net/GUxD2j If you're using .NET 4.5: https://dotnetfiddle.net/NirDuU . 如果您使用的是.NET 4.5: https//dotnetfiddle.net/NirDuU This sample shows the use of the new await/ async pattern introduced in the .NET framework 此示例说明了.NET框架中引入的新await / async模式的使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM