0

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.

leon
  • 435
  • 1
  • 4
  • 12
  • if you mark your worker thread as background, you don't need to abort it yourself - it won't prevent the app from exiting. – James Manning Jul 14 '10 at 06:11

2 Answers2

1

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 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 Jul 14 '10 at 06:14
  • 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 Jul 14 '10 at 07:18
0

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

Community
  • 1
  • 1
KMån
  • 9,896
  • 2
  • 31
  • 41