Stijn De Cat
Stijn De Cat

Reputation: 81

How do I kill a playloop when a thread is killed?

Meet Thread:

    public void TimerFunc(){
        ...
        while (true)
        {
  ...
                sound.PlayLooping();
                // Displays the MessageBox and waits for user input
                MessageBox.Show(message, caption, buttons);
                // End the sound loop
                sound.Stop();
 ...

        }
    }

Thread gets started by a button in the main interface, and can get killed by a button in the interface.

How do i get the soundloop to stop if the thread gets killed when waiting for user input?

Upvotes: 2

Views: 1085

Answers (1)

Giulio Franco
Giulio Franco

Reputation: 3230

You DO NOT kill the thread. If the thread is killed, it can't do anything.

Just politely send a message to the thread, asking it to stop playing.

private volatile bool canContinue = true;

public void TimerFunc(){
    ...
    while (true && canContinue)
    {
        ...
        sound.PlayLooping();
        // Displays the MessageBox and waits for user input
        MessageBox.Show(message, caption, buttons);
        // End the sound loop
        sound.Stop();
        ...
    }
}

public void StopPolitely()
{
    canContinue = false;
}

The button on the main interface will then just call thread.StopPolitely() and terminate the thread in a clean way. If you want it to terminate faster, you may consider other and more aggressive solutions, such as checking canContinue more often, or using Thread.Interrupt() to wake the thread even if it's busy in a blocking call (but then you have to manage the interrupt) Since it's just a bool, and it's single-writer/single-reader, you can even avoid declaring it as volatile, even though you should.

Upvotes: 2

Related Questions