无法正确停止 c# 中的所有线程
Cannot stop properly all threads in 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);
});
}`
用检查器调用的函数构建如下:
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
我正在尝试在 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);
});
}`
用检查器调用的函数构建如下:
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