在停止线程池.NET全部线程? [英] Stopping all thread in .NET ThreadPool?

查看:153
本文介绍了在停止线程池.NET全部线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用线程池在.NET做的背景下一些web请求,我希望有一个停止按钮取消,即使他们是在发出请求的中间,这样一个简单的布尔的所有线程不会做的工作。

I am using ThreadPool in .NET to make some web request in the background, and I want to have a "Stop" button to cancel all the threads even if they are in the middle of making a request, so a simple bool wont do the job.

我怎么能这样做?

推荐答案

到正确的操作方法是让你的信号标志对象。

The correct way to handle this is to have a flag object that you signal.

在这些线程中运行的代码需要定期检查标志,看它是否应该退出

The code running in those threads needs to check that flag periodically to see if it should exit.

例如,的 ManualResetEvent的对象适用于本

您可以再问问线程退出是这样的:

You could then ask the threads to exit like this:

evt.Set();

和线程里面,你会检查它是这样的:

and inside the threads you would check for it like this:

if (evt.WaitOne(0))
    return; // or otherwise exit the thread



其次,由于您使用的线程池,会发生什么情况是所有你排队的项目仍然会进行处理,但如果添加到上面线程方法的一开始的if语句,它会立即退出。如果这还不够好,你应该建立使用普通线程自己的系统,这样,你有完全的控制权。

Secondly, since you're using the thread pool, what happens is that all the items you've queued up will still be processed, but if you add the if-statement above to the very start of the thread method, it will exit immediately. If that is not good enough you should build your own system using normal threads, that way you have complete control.

哦,只是为了确保,做不可以使用Thread.Abort的。问线程退出很好,不直接杀了他们。

Oh, and just to make sure, do not use Thread.Abort. Ask the threads to exit nicely, do not outright kill them.

这篇关于在停止线程池.NET全部线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆