C# BackgroundWorker多线程怎么用一个按钮来重新启动呢?
如下代码,Button_Click的开始是正常,Button_Click_1的停止也是正常的。
想要做到的效果是点击Button_Click_2,判断线程如果是取消了的,就开启,如果是开启的就取消了重新的开启。
也就是将Button_Click和Button_Click_1的功能通过一个按钮来实现。
Button_Click_2方法中这样的写法运行到后面会报BackgroundWorker调用线程无法访问此对象,因为另一个线程拥有该对象。的错误
/// <summary>
/// 开始执行后台操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
if (ordernChangedWorker.IsBusy == false)
{
textLB.Content = "开始了";
ordernChangedWorker.RunWorkerAsync();
}
}
/// <summary>
/// 取消,停止
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show("取消中");
ordernChangedWorker.CancelAsync();
}
/// <summary>
/// 重新开始
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_2(object sender, RoutedEventArgs e)
{
if (ordernChangedWorker.IsBusy)
{
MessageBox.Show("取消中");
ordernChangedWorker.CancelAsync();
//取消后,用线程判断IsBusy,等待继续启动
new Thread((ThreadStart)(delegate()
{
while (ordernChangedWorker.IsBusy)
{
Thread.Sleep(100);
}
ordernChangedWorker.RunWorkerAsync();
})).Start();
}
else
{
ordernChangedWorker.RunWorkerAsync();
}
}