见面主题:
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();
...
}
}
线程可以通过主界面中的按钮启动,也可以通过界面中的按钮终止。
如果线程在等待用户输入时被终止,如何让声音循环停止?
最佳答案
你不要杀死线程。如果线程被杀死,它就不能做任何事情。
只需礼貌地向该线程发送一条消息,要求其停止播放即可。
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()
来唤醒线程如果它正忙于阻塞调用(但是你必须管理中断)
由于它只是一个 bool 值,并且是单写入器/单读取器,因此您甚至可以避免将其声明为 volatile
,即使您应该这样做。
关于c# - 当线程被杀死时如何杀死播放循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221785/