Error returns when trying to start some threads in a list

Asked

Viewed 464 times

2

I need to create a function for my program, which when the user is pressing the NUMPAD_8, he shut down all the thread, and if he squeezes again, he turns them back on.

How 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 the 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 well, but the .Start() returns me the following error:

System.Threading.Threadstateexception: 'Thread is running or has been terminated. Cannot be restarted.'

1 answer

3


Error happens because a Thread cannot be restarted.

You must recall the method addThreads() for them to be recreated.

Add to the method

threads.Clear();

for the list to be cleaned.

You have to change the logic within the if because it cannot be done in the else.

Bear in mind that:

  • Instead of using foreach and if, I could do that with the .forEach.Where? I acknowledge that this is outside the scope of the question, but you can help me with that?

  • Not because it "does not exist" ForEach.Where. ForEach returns void. How much Where.ToList.ForEach.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.