c# - 无法正确停止 c# 中的所有线程
问题描述
我正在尝试在 c# 中使用令牌或 thread.abort 停止所有线程,但两者都无法正常工作
int workerThreads = 1;
int portThreads = 0;
ThreadPool.SetMinThreads(workerThreads, portThreads);
ThreadPool.SetMaxThreads(workerThreads,portThreads);
foreach (string d in list)
{
var p = d;
ThreadPool.QueueUserWorkItem((c) =>
{
this.checker(p,cts.Token);
});
}`
使用 checker 调用的函数构建如下:
private void checker(string f, object obj)
{
try
{
CancellationToken token = (CancellationToken)obj;
if (token.IsCancellationRequested)
{
MessageBox.Show("Stopped", "Checker aborted");
token.ThrowIfCancellationRequested();
cts = new CancellationTokenSource();
} //etc main features of fucntion are hidden from here
当我调用 cts.Cancel(); 时,我想正确停止所有线程;但每次都会出现: Stopped , checker aborted 并且不仅是一次,而且可能会为每个线程进程显示。如何一次显示消息并在同一时刻停止所有线程?我还想设置一些在处理其他线程之前应该工作的最大线程数。我尝试使用 SetMaxThreads,但这似乎都不起作用。
解决方案
请参阅评论以获取最佳实践建议,因为您在这里所做的并不完全正确,但为了实现您的目标,您可以使用标志与锁结合,如下所示:
private static object _lock = new object();
private static bool _stoppedNotificationShown = false;
private void checker(string f, object obj)
{
try
{
CancellationToken token = (CancellationToken)obj;
if (token.IsCancellationRequested)
{
lock(_lock) {
if (!_stoppedNotificationShown) {
_stoppedNotificationShown = true;
MessageBox.Show("Stopped", "Checker aborted");
}
}
token.ThrowIfCancellationRequested();
cts = new CancellationTokenSource();
} //etc main features of fucntion are hidden from here
推荐阅读
- django - 我如何在 django 中给出限制?
- postgresql - 如何在 gitlab 综合 docker 容器或远程终端访问/登录 postgres?
- php - 仅使用 Htaccess 删除指定 URL 的子文件夹 [Codeigniter]
- swift - 带有参数标签的 Swift 下标
- python - 将 groupby 系列与数据框合并
- dynamics-crm - Dynamics 365 重新激活潜在客户
- javascript - Bootstrap Datetimepicker Remaing 秒数
- docker - 沙盒代理容器在启动后不久崩溃
- jmeter - 以随机顺序执行场景中的请求 [Taurus/JMeter]
- sql - INSERT a SELECT GROUP BY : more target columns than expressions 错误