Is The reuse of the backgroundworker object possible?
I have a button "refresh" which every time i click on it i want my backgroundworker object to work.
i use
if (main_news_back_worker.IsBusy != true)
开发者_运维问答 {
// Start the asynchronous operation.
main_news_back_worker.RunWorkerAsync();
}
private void main_news_back_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
show_system_urls(urls);
displayNewMes(newMes, newStock, newSource);
displayOldMes(oldMes, oldStock);
}
The first time i use the backgroundworker it work good and also get to the RunWorkerCompleted and do his work. But the second time i try to run the object the is_busy property of the object is 'true' and i cant run the object again...
Do i need to create a new backgroundworker every time i want to run it? how do i do it? Thanks.
Yes, no problem. You will however have to make sure that the user cannot click the button again while the BGW is busy. Easily done by setting the Enabled property, stops the button action and provides excellent visual feedback to the user. Try this for example:
private void button1_Click(object sender, EventArgs e) {
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
System.Threading.Thread.Sleep(2000);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
button1.Enabled = true;
}
But the second time i try to run the object the is_busy property of the object is 'true'
That means the first background action is still running.
You will first have to decide if you want 2 of these actions to be going on at the same time.
If No, implement Cancellation so that you can Stop (and then restart) the Bgw.
If Yes, create a new Bgw each time.
And while you can re-use a Bgw, and that makes sense in the 1st scenario, there is no great saving in doing so. The Bgw Thread comes from the ThreadPool and will be re-used anyway.
精彩评论