2014-04-02 90 views
0

是否可以在运行时向后台工作人员添加回调?我可以添加回调到已经运行的BackgroundWorker吗?

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

bw.RunWorkerAsync(); 

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

谢谢。

+1

是的,你能够。但那不会被称为我想 –

+0

@SriramSakthivel谢谢。有没有办法将任务放入队列中? – Virus721

+2

您可以使用'Queue'类来实现此目的,将工作项添加到它,然后逐个处理。另一个选择是使用'BlockingCollection' –

回答

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(); 
} 
相关问题