我可以向已经运行的BackgroundWorker添加回调吗?

时间:2014-04-02 11:29:12

标签: c# multithreading events callback

是否可以在后台工作程序运行时添加回调?

bw.DoWork += new DoWorkEventHandler( some callback );

bw.RunWorkerAsync();

bw.DoWork += new DoWorkEventHandler( some callback );

谢谢。

1 个答案:

答案 0 :(得分:1)

是的,你可以,因为它只是对某个活动的订阅,但是在他完成第一个任务的执行之前你不能运行bw

此处举例说明以下代码将显示InvalidOperationException告诉此 BackgroundWorker is currently busy and cannot run multiple tasks concurrently."

public partial class Form1 : Form
    {                       
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerAsync();
            backgroundWorker1.DoWork+=new DoWorkEventHandler(backgroundWorker2_DoWork);
            //at this line you get an InvalidOperationException
            backgroundWorker1.RunWorkerAsync();




        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            do
            {

            } while (true);
        }
        void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            do
            {

            } while (true);
        }
       }

作为对您的评论问题的回答

@SriramSakthivel Thanks. Is there a way to put tasks in a queue ?

是的,如果您使用的是.net 4.0,则可以将任务与ContinueWith一起使用并将其附加到您的UI taskScheduler它将具有与使用BackgroundWorker

相同的行为
private void TestButton_Click(object sender, EventArgs e)
{
    TestButton.Enabled = false;
    var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();

    var backgroundTask = new Task(() =>
    {
        Thread.Sleep(5000);
    });

    var uiTask = backgroundTask.ContinueWith(t =>
    {
        TestButton.Enabled = true;
    }, uiThreadScheduler);

    backgroundTask.Start();
}