Reputation: 1577
I got below error when I used of thread for called waiting form during a long process.
"An unhandled exception of type 'System.Threading.ThreadAbortException' occurred in System.Windows.Forms.dll
Additional information: Thread was being aborted."
Sometimes my code works well but sometimes this error occurred.
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;
}
}
I got this error on showProgressForm()
Method on sform.ShowDialog()
Line
and the main program I called this class looks like this:
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();
any Idea?
Upvotes: 4
Views: 4337
Reputation: 1577
tnx all. i changed my Progress Class code like this:
//private static Thread th = new Thread(new ThreadStart(showProgressForm));
private static Thread th;
public void startProgress()
{
th = new Thread(new ThreadStart(showProgressForm));
th.Start();
}
and it's worked
Upvotes: 1
Reputation: 3043
private static Thread th = new Thread(new ThreadStart(showProgressForm));
public void startProgress()
{
th = new Thread(new ThreadStart(showProgressForm));
th.Start();
}
Not a big deal, but why do you instantiate your thread twice? Not really clean. I think only the one in your ctor is mandatory, because you set th = null when calling stopProgress().
Anyway look at your code, and remember that thread are asynchronous, so:
ProgressCLS PC = new ProgressCLS();
PC.startProgress();
It runs your progress form in a dedicated thread (asynchronous, so your code is still running).
TodayDate = txtDate.SelectedDateTime.ToString("yy-MM-dd");
ClearField();
CalculateMSG();
...
You perform a serie of process in the main thread (synchrounously, your progress form still running in the background).
PC.stopProgress();
Whatever the status of your progress form, it is aborted. And as you might have missed from the MSDN documentation, it "Raises a ThreadAbortException in the thread on which it is invoked". Thus to be fair, it is even Strange that your code "sometimes work", because if it hits the th.Abort() line, it should failed.
A few hints here:
Upvotes: 2