【发布时间】:2016-09-28 09:14:27
【问题描述】:
当我在一个漫长的过程中使用线程来调用等待表单时出现以下错误。
"一个未处理的异常类型 'System.Threading.ThreadAbortException' 发生在 System.Windows.Forms.dll
附加信息:线程被中止。"
有时我的代码运行良好,但有时会出现此错误。
class ProgressCLS
{
private static Thread th = new Thread(new ThreadStart(showProgressForm));
public void startProgress()
{
th = new Thread(new ThreadStart(showProgressForm));
th.Start();
}
private static void showProgressForm()
{
Waiting sForm = new Waiting();
sForm.ShowDialog();
}
public void stopProgress()
{
th.Abort();
th = null;
}
}
我在showProgressForm() 方法上收到此错误sform.ShowDialog() 行
我调用这个类的主程序是这样的:
ProgressCLS PC = new ProgressCLS();
PC.startProgress();
TodayDate = txtDate.SelectedDateTime.ToString("yy-MM-dd");
ClearField();
CalculateMSG();
tabControl1.SelectedIndex = 1;
btnShowFolderLocal.Enabled = true;
btnShowFolderTop.Enabled = true;
btnShowDpsFailed.Enabled = true;
btnShowDpsFailed2.Enabled = true;
btnShowFolderTopic.Enabled = true;
ShowMSGButtonClicked = true;
PC.stopProgress();
有什么想法吗?
【问题讨论】:
-
那是因为您使用了 Thread.Abort() 并且您有一个未发布的 try/catch-em-all 语句。不要捕获 ThreadAbortException。
-
您不需要单独的线程来显示进度表。显示带有
Show而不是ShowDialog的非模态 表单。如果您想报告另一个任务/线程的进度,请使用Progress<T>并订阅其事件 -
其实不要用
Thread.Abort。它可能不再是曾经的大坏丑狼,但它仍然是一种非常糟糕的代码味道,有很多方法可以处理这种类型的事情没有Thread.Abort.
标签: c# multithreading winforms progress