我正在尝试使用C#停止所有带有token或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,检查程序异常终止,不仅一次,而且可能在每个线程进程中都显示。如何显示消息一次并同时停止所有线程? 我还要设置一些最大线程数,然后再继续其他线程。我尝试了SetMaxThreads,但是这似乎都不起作用。
答案 0 :(得分:1)
请参考注释以获取最佳实践建议,因为您在此处所做的操作并不完全正确,但是要实现您的目标,您可以使用带有锁的标志,如下所示:
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