3

I'm only starting learning c# (and programming in general). I'm doing a little college project that plays music based on strings. I'm using windows forms. When you press the "play" button a it starts a method with a for loop that goes through each character in the string one by one and plays the appropriate note. Works fine, but I've been trying to add a "stop" button that will stop the music as its playing, but so far when the music is playing the form is frozen and I cant hit any other buttons... Just wondering is the only way I can achieve what I want by having different threads?? (We havent really looked at threads yet!)

edit: Hey thanks all for answers!! that was very very fast! :)

4

4 回答 4

4

查看BackgroundWorker 类以在后台播放音乐。它比自己操作线程简单得多。

这是一个概述:

http://www.albahari.com/threading/part3.aspx#%5FBackgroundWorker

于 2012-06-14T01:20:26.683 回答
3

只是想知道通过使用不同的线程来实现我想要的唯一方法是什么?

通常,这是发生这种情况的最常见方法。我建议看一下BackgroundWorker组件。它允许您在后台线程上运行工作(“播放音符”),但也提供取消支持。

于 2012-06-14T01:19:38.300 回答
1

您的问题的简单答案是肯定的。

您正在主线程上循环播放音乐,这意味着当代码在循环中执行时,您无法从 UI 接收任何事件。

要解决此问题,您需要在后台线程上运行音乐循环。

于 2012-06-14T01:20:11.060 回答
0

Application.DoEvents();如果您还不想使用线程,请在每次迭代后使用。Theads 是最好的解决方案,但正如我理解你的问题,当你首先学习线程时你正在等待:) 调用DoEvents()允许在调用它时处理窗口消息,所以如果你经常调用它,窗口不应该被阻塞。但请将此视为一种解决方法,而不是最佳解决方案。最好的灵魂将使用线程。

于 2012-06-14T01:20:19.870 回答