How to run a thread several times in c #?

-1

Why do I have an exception?

Thread hs;
hs = new Thread(()=>Playsound(sound));


while (bstate==-1)
{
    t = Int16.Parse(bpm.Text);
    t = 60000 / t;

    hs.Start();

    cajas[compas-1].Fill = new SolidColorBrush(Colors.White);
    cajas[0].Fill = new SolidColorBrush(Colors.Red);
    await Task.Delay(t);

    for (int k = 1; k < compas-1; k++)
    {


        hs.Start();
        cajas[k-1].Fill = new SolidColorBrush(Colors.White);
        cajas[k].Fill = new SolidColorBrush(Colors.Black);
        await Task.Delay(t);
    }

    hs.Start();

    cajas[compas - 2].Fill = new SolidColorBrush(Colors.White);
    cajas[compas - 1].Fill = new SolidColorBrush(Colors.Black);
    await Task.Delay(t);

}

Text of the exception:

  

System.Threading.ThreadStateException: 'Thread running or terminated; it can not be restarted. ' The exception occurs in the second hs.Start ();

    
asked by Edgar Diaz 18.11.2017 в 09:57
source

1 answer

1

The error tells you exactly what happens. A% co_of% that has ended can not be reused, which is explained in the documentation of Thread.Start

  

Once the thread ends, it can not be restarted with another call to Start.

That is

  

Once the thread ends, it can not be restarted with another call to Start.

The solution would be to re-create an instance of the thread (make thread before each hs = new Thread(()=>Playsound(sound)); ); or maybe use ThreadPool.

Anyway, I will never tire of recommending not to use the Thread class . It is an old class and very difficult to use correctly, and .Net provides much more adequate, modern and simple substitutes: BackgroundWorker and Task .

    
answered by 20.11.2017 в 13:00