简体   繁体   中英

Stop Threads created with ThreadPool.QueueUserWorkItem that have a specific task

Let's say I queue those two methods in a for loop

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output");
        Thread.Sleep(1000);
    });
}

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output2");
        Thread.Sleep(1000);
    });
}

Is there a way to stop all the threads that output Console.WriteLine("Output2"); but keep the ones running that output Console.WriteLine("Output"); ?

You could use a CancellationToken:

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output");
        Thread.Sleep(1000);
    });
}

CancellationTokenSource cts = new CancellationTokenSource();

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        CancellationToken token = (CancellationToken) s;
        if (token.IsCancellationRequested)
            return;
        Console.WriteLine("Output2");
        token.WaitHandle.WaitOne(1000);
    }, cts.Token);
}

cts.Cancel();

No, you can't do that. If you want to do something a long the lines then you must write some code to manage it. At the very basic level you need something like this:

object syncObject = new object();
bool shouldOutput2 = true;
ThreadPool.QueueUserWorkItem(s =>
{
    lock(syncObject)
    {
        if(!shouldOutput2)
        {
           return;
        }
    }
    Console.WriteLine("Output2");
    Thread.Sleep(1000);
});

Once you queue the items, then you can set the flag in order to tell the remaining items not to execute:

   lock(syncObject)
   {
        shouldOutput2 = false;
   }

This is a very dirty way of doing it, but it seems like the only way given your example. If you can tell us more about what is the actual real-world behavior you're trying to accomplish, then there could be some better options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM