Click here to Skip to main content
15,886,740 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
WHEN I ABORT THE THREAD AN EXCEPTION OCCURS THAT THREAD HAS BEEN ABORTED
IS THERE ANY WAY TO REMOVE THIS EXCEPTION....



[Same Question without all the capitals]

When I abort the thread an exception occurs that thread has been aborted
Is there any way to remove this exception........
Posted
Updated 26-May-23 5:07am
v2
Comments
LittleYellowBird 12-Jul-10 9:39am    
It is best not to use capitals as it looks like shouting and is therefore very rude, it is worth reading the notes when you post a question as these tell you that, as well as other handy hints to get your question answered. Ali :)

Not that i've ever found, i simply catch it and move on. I believe it was done so that the code running in that thread has a way to know its stopping. That way you can catch the exception and do whatever clean up you need (i think Finally's will still run) before the thread goes away.

I havent really messed with Threads or winForms since .NET 1.1, so something may have changed. Feel free to correct me if i'm wrong.
 
Share this answer
 
No. The purpose of the ThreadAbortException is to notify aborted threads that it's time to cleanup after itself and release any resources that it might be holding. If a thread doesn't have an opportunity to do this it could leave the application in an inconsistent - that means anything from leaking resources to corrupted memory - and that will most likely cause an application crash later on down the line.

Aborting threads is considered bad practice for this reason. Instead of using Thread.Abort(), it's better to work out a cooperative method of notifying threads that it's time to exit so that they can take care of exiting cleanly to maintain the consistency of the program.
 
Share this answer
 
SomeGuyThatIsMe is right. As you can read on the MSDN documentation about Thread.Abort Method (System.Threading)[^]:

"When this method is invoked on a thread, the system throws a ThreadAbortException in the thread to abort it. ThreadAbortException is a special exception that can be caught by application code, but is re-thrown at the end of the catch block unless ResetAbort is called. ResetAbort cancels the request to abort, and prevents the ThreadAbortException from terminating the thread. Unexecuted finally blocks are executed before the thread is aborted."

This will give the thread a chance to cleanup the resources that it could have allocated, and to reject the request to abort.

If you don't need any cleanup, simply wrap your thread method inside a try/catch block.
 
Share this answer
 
Comments
haseebsvirgo 13-Jul-10 1:09am    
//*BUTTON DOWNLOAD*//

private void btnDownload_Click(object sender, EventArgs e)
{
btnDownload.Enabled = false;
btnResume.Enabled = false;
btnPause.Enabled = true;
btnStop.Enabled = true;

if (thrDownload != null && thrDownload.ThreadState == ThreadState.Running)
{
MessageBox.Show("Download in progress!Please wait for download to complete or stop it", "Download In Progress", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (DownloadGrid.CurrentRow != null && Convert.ToString(DownloadGrid.CurrentRow.Cells["IPAddress"].Value) != string.Empty)
{
txtServerIP.Text = Convert.ToString(DownloadGrid.CurrentRow.Cells["IPAddress"].Value);
}

if (txtServerIP.Text != "ftp://" && txtServerIP.Text != string.Empty)
if (txtFileName.Text != string.Empty)
{
thrDownload = new Thread(new ThreadStart(delegate { downloadFile(txtServerIP.Text, txtFileName.Text, txtUsername.Text, txtPassword.Text); }));
thrDownload.Start();
saveFile1.FileName = txtFileName.Text;
}
else
MessageBox.Show("Please enter a file name or click the Get File List button");
else
MessageBox.Show("No server found");
}
}

//*FUNCTION DOWNLOAD FILE*//

private byte[] downloadedData;
private void downloadFile(string FTPAddress, string filename, string username, string password)
{
downloadedData = new byte[0];

try
{
//Optional
this.Text = "Connecting...";
Application.DoEvents();

//Create FTP request
// format is ftp://server.com/file.ext
FtpWebRequest request = FtpWebRequest.Create("ftp://" + FTPAddress + "/" + filename) as FtpWebRequest;
//Optional
this.Text = "Retrieving Information...";
Application.DoEvents();

//Get the file size first (for progress bar)
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true; //don't close the connection

int dataLength = (int)request.GetResponse().ContentLength;

//Optional
this.Text = "Downloading File...";
Application.DoEvents();

//Now get the actual data
request = FtpWebRequest.Create("ftp://" + FTPAddress + "/" + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false; //close the connection when done

//Set up progress bar
progressBar1.Value = 0;
progressBar1.Maximum = dataLength;
lbProgress.Text = "0/" + dataLength.ToString();


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


haseebsvirgo 13-Jul-10 1:10am    
//Streams
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream reader = response.GetResponseStream();

//Download to memory
//Note: adjust the streams here to download directly to the hard drive
MemoryStream memStream = new MemoryStream();
byte[] buffer = new byte[1024]; //downloads in chuncks


while (true)
{
Application.DoEvents(); //prevent application from crashing

//Try to read the data
int bytesRead = reader.Read(buffer, 0, buffer.Length);
bytecount++;
if (bytesRead == 0)
{
//Nothing was read, finished downloading
progressBar1.Value = progressBar1.Maximum;
lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString();

Application.DoEvents();
break;
}
else
{
//Write the downloaded data
memStream.Write(buffer, 0, bytesRead);

//Update the progress bar
if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
{
progressBar1.Value += bytesRead;
lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString();

progressBar1.Refresh();
Application.DoEvents();
}
}
}

//Convert the downloaded stream to a byte array
downloadedData = memStream.ToArray();

//Clean up
reader.Close();
memStream.Close();
response.Close();

btnResume.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;

MessageBox.Show("File Downloaded Successfully");


}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}

txtData.Text = downloadedData.Length.ToString();
this.Text = "Download Data through FTP";

username = string.Empty;
password = string.Empty;
}
haseebsvirgo 13-Jul-10 1:14am    
//*BUTTON STOP*//
private void btnStop_Click(object sender, EventArgs e)
{


btnDownload.Enabled = true;
btnPause.Enabled = false;
thrDownload.Abort();
//response.Close();
//reader.Close();
//memStream.Close();
progressBar1.Value = 0;
lbProgress.Text = "0/0";

}



this is the piece of code it all works fine when press download and the thread will start
when i click stop button
thread.abort is executed with a teasing message that thread has been aborted .
i donot want this message to be displayed
i want to display a message that "download cancelled" rather than exception message"THREAD HAS BEEN ABORTED"


PLEASE ITS A HUMBLE REQUEST DO HELP ME ....
Sauro Viti 13-Jul-10 3:00am    
You are using an anonimous delegate from which you call your function. You should try/catch the ThreadAbortException at the most external level, then you should do it inside your delegate, like this:

thrDownload = new Thread(new ThreadStart(
delegate
{
try
{
downloadFile(txtServerIP.Text, txtFileName.Text, txtUsername.Text, txtPassword.Text);
}
catch (ThreadAbortException ex)
{
MessageBox.Show("Download aborted");
}
}));
Hello,

For the Issues: "thread has been aborted exception message"

please use the catch block as like bellow:
try
{
...
...

}
catch (ThreadAbortException ex)
{
Thread.ResetAbort();
}

Thanks & Regards
Abhay Malviya
 
Share this answer
 
Comments
Richard Deeming 30-May-23 5:14am    
Aside from the fact that you're 10 years late; and the fact that resetting the abort would cancel the abort request, changing the meaning of the original code; there's also the fact that this method is no longer supported:

Thread.ResetAbort Method (System.Threading) | Microsoft Learn[^]
"Thread.ResetAbort is not supported and throws PlatformNotSupportedException."

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900