在我的场景中中止线程的最佳方法是什么
如果其他人之前问过类似的问题,我很抱歉。 我有一个简单的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,你上传得怎么样?
Thread.Abort
很少是一个明智的选择 - 它可以让您的AppDomain
(甚至Process
)完全陷入困境。混乱的状态。如果您通过http上传,您可以尝试使用异步方法,允许您调用HttpWebRequest.Abort
,这更友好一些。Well, how are you uploading?
Thread.Abort
is rarely a sensible choice - it can leave youAppDomain
(or evenProcess
) in a completely messed-up state. If you are uploading via http, you could try using the async methods, allowing you to callHttpWebRequest.Abort
, which is a bit more friendly.顺便说一句,这只是对马克所说的进行补充,这个答案可能有助于理解为什么
.Abort
不是一个好的选择。Btw, this is just to add to what Marc said, this answer might help understand why
.Abort
is not so a good choice.