What's the best way to abort a thread in my scenerio
I'm sorry if some other people have asked a similar question before. I have a simple GUI app which upload some files to a server. I put the upload work to a seperate thread. When users want to exit the application, a event will be set to notify the thread to exit normally. Then the UI thread will wait for it. The code I used to abort the thread is as follows:-
if (mUploadThread != null) {
if (mStopUploadEvent.WaitOne(0, true)) {
string message = @"A normal cancellation may take a couple of minutes. Are you sure you want forcibly abort?";
string caption = @"Warning";
if (DialogResult.Yes == MessageBox.Show(message, caption, MessageBoxButtons.YesNo)) {
mUploadThread.Abort();
}
} else {
mStopUploadEvent.Set();
}
do {
Application.DoEvents();
} while (!mUploadThread.Join(1000));
}
Here I want to terminate the worker thread if the user do want to. But the abort() method just doe开发者_如何学Pythonsn't work. Any suggestion is appreciated.
Well, how are you uploading? Thread.Abort
is rarely a sensible choice - it can leave you AppDomain
(or even Process
) in a completely messed-up state. If you are uploading via http, you could try using the async methods, allowing you to call HttpWebRequest.Abort
, which is a bit more friendly.
Btw, this is just to add to what Marc said, this answer might help understand why .Abort
is not so a good choice.
精彩评论