当线程被杀死时如何杀死播放循环?

遇见线程:

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

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

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

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

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

 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 ,即使你应该。