2

见面主题:

    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();
 ...

        }
    }

线程由主界面中的按钮启动,并且可以被界面中的按钮杀死。

如果线程在等待用户输入时被杀死,我如何让声音循环停止?

4

1 回答 1

2

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

只是礼貌地向线程发送消息,要求它停止播放。

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()即使线程在阻塞调用中忙,也可以使用它来唤醒线程(但是您必须管理中断)因为它只是一个布尔值,它是单写者/单读者,你甚至可以避免将其声明为volatile,即使你应该这样做。

于 2013-08-14T01:39:53.317 回答