不确定我的标题是否措辞得当,但无论如何 :)
我有两个线程:主线程需要完成工作,工作线程包含一个带有进度条和取消按钮的表单。在正常代码中,它会反过来,但在这种情况下我不能那样做。
当用户点击取消按钮时,会弹出一个提示,询问他是否真的要取消这个工作。问题是工作在主线程上继续进行。我可以让主线程停止工作等,但我希望当他在提示中单击"is"时它停止工作。
例子:
// Main thread work starts here
t1 = new Thread(new ThreadStart(progressForm_Start));
t1.Start();
// Working
for (i = 0; i <= 10000; i++)
{
semaphore.WaitOne();
if (pBar.Running)
bgworker_ProgressChanged(i);
semaphore.Release();
if (pBar.IsCancelled) break;
}
t1.Abort();
// Main thread work ends here
// Start progress bar form in another thread
void progressForm_Start()
{
pBar.Status("Starting");
pBar.ShowDialog();
}
理论上我可以在 cancelWatch() 函数中包含一个提示,但是我必须在实现这个类的所有地方都这样做。
请您参考如下方法:
我有几个简短的评论:
- 避免使用
Thread.Abort()here's why . - 让您的线程成为后台线程:
Thread.IsBackground = true(这将在您的应用退出时自动退出线程)。
这里是关于如何安全停止线程运行的详细讨论:Is it safe to use a boolean flag to stop a thread from running in C#
要停止主线程上的工作,您必须执行如下操作:
boolean volatile isRunning = true;
static void Main(...)
{
// ...
// Working
for (i = 0; i <= 10000; i++)
{
semaphore.WaitOne();
if (!isRunning) break; // exit if not running
if (pBar.Running)
bgworker_ProgressChanged(i);
semaphore.Release();
}
//...
t1.Interrupt();// make the worker thread catch the exception
}
//
void cancelButton_Click(object sender, EventArgs e)
{
isRunning = false; // optimistic stop
semaphore.Release();
}
