views:

65

answers:

2

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 doesn't work. Any suggestion is appreciated.

+1  A: 

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.

Marc Gravell
fully agree on not using Thread.Abort normally, but it sounds like this is a scenario where he's about to exit the entire process anyway AFAICT.
James Manning
I know Abort is not a good choice, that's why I use event to notify the thread to exit first. Yes I think I should use the async http methods. Thank you.
leon
A: 

Btw, this is just to add to what Marc said, this answer might help understand why .Abort is not so a good choice.

KMan
Which he does... `do { Application.DoEvents(); } while (!mUploadThread.Join(1000));`
Marc Gravell
@Marc: Missed that part; removed from my answer.
KMan