在我的场景中中止线程的最佳方法是什么

发布于 2024-09-09 19:19:56 字数 672 浏览 3 评论 0原文

如果其他人之前问过类似的问题,我很抱歉。 我有一个简单的 GUI 应用程序,它将一些文件上传到服务器。我把上传工作放在一个单独的线程中。当用户想要退出应用程序时,会设置一个事件来通知线程正常退出。然后UI线程会等待它。我用来中止线程的代码如下:-

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));
 }

这里,如果用户确实愿意,我想终止工作线程。但 abort() 方法不起作用。任何建议表示赞赏。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦初启 2024-09-16 19:19:56

嗯,你上传得怎么样? Thread.Abort很少是一个明智的选择 - 它可以让您的AppDomain(甚至Process)完全陷入困境。混乱的状态。如果您通过http上传,您可以尝试使用异步方法,允许您调用HttpWebRequest.Abort,这更友好一些。

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.

孤檠 2024-09-16 19:19:56

顺便说一句,这只是对马克所说的进行补充,这个答案可能有助于理解为什么.Abort不是一个好的选择。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文