我如何杀死一个playloop当一个线程被杀害?线程、被杀、playloop

2023-09-03 21:48:50 作者:sake(清酒)

相约主题:

    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.

如何等待用户输入时,我得到的soundloop停止,如果线程就会被杀死?

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

推荐答案

你不杀线程。如果线程被杀害,它不能做任何事情。

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;
}

在主界面上的按钮就可以致电 thread.StopPolitely()并终止线程在一个干净的方式。 如果你想让它停止更快,你可能会考虑其他更激进的解决方案,如检查 canContinue 更多的时候,或者使用了Thread.interrupt() 来唤醒线程即使是忙碌的阻塞调用(但你必须管理的中断) 因为它只是一个布尔值,它的单写/单读取器,你甚至可以避开它声明为挥发性,即使你应该。

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.

 
精彩推荐
图片推荐