Error returns when trying to start some threads in a list

2

I need to create a function for my program, that when the user is pressing NUMPAD_8 , it turns off all thread , and if he presses again, it turns them back on.

As I'm creating the thread list:

public static List<Thread> threads = new List<Thread>();

public static void addThreads()
{
    threads.Add(new Thread());
    threads.Add(new Thread());
    threads.Add(new Thread());
    threads.Add(new Thread());
    threads.Add(new Thread());
    threads.Add(new Thread());
    threads.Add(new Thread());
    //Só deixei em branco o Thread() para ilustrar melhor o problema,
    //em meu programa eles estão preenchidos todos corretamente.
}

How I'm starting threads:

Vars.addThreads();
foreach (Thread t in Vars.threads)
{
    t.Start();
}

How I tried:

if (Gambiarras.ChecarPressionando(0x68))
{
    foreach (Thread t in Vars.threads)
    {
        if (t.ThreadState == System.Threading.ThreadState.Running)
            t.Abort();
        else
            t.Start();
    }
    Thread.Sleep(1000);
}

The .Abort() works fine, but the .Start() returns the following error:

  

System.Threading.ThreadStateException: 'The thread is either running or has been shut down. It can not be restarted. '

    
asked by anonymous 04.08.2017 / 15:34

1 answer

3

The error happens because a Thread can not be restarted.

You must call the addThreads() method again to recreate them.

Add to method

threads.Clear();

to make the list clean.

You will have to change the logic within if because this can not be done in else .

Please note:

04.08.2017 / 15:45