在问之前,我先给出一些代码..。
public partial class Player : UserControl
{
ManualResetEvent _pauseEvent;
ManualResetEvent _stopEvent;
Thread t;
public Player()
{
InitializeComponent();
this.Disposed += (s, a) =>
{
Quit();
};
_pauseEvent = new ManualResetEvent(true);
_stopEvent = new ManualResetEvent(false);
// Creates the thread...
t = new Thread(StartText);
t.IsBackground = false;
// Starts with thread paused...
StopPlaying();
// Let's go!
t.Start();
}
public void StopPlaying()
{
Console.WriteLine("Ordered to stop");
_pauseEvent.Reset();
}
private void ResumePlaying()
{
Console.WriteLine("Ordered to resume");
_pauseEvent.Set();
}
public void Quit()
{
_pauseEvent.Set();
_stopEvent.Set();
}
public void SetText(string text, bool loop)
{
StopPlaying();
// Here we supose the thread would be stopped!!!! But it's not!!!
// But when I call StopPlaying() from a button on the form that
// contains this usercontrol, everything works as expected
...... Do some processing here .....
ResumePlaying();
}
private void StartText()
{
while (true)
{
_pauseEvent.WaitOne(Timeout.Infinite);
if (_stopEvent.WaitOne(0))
break;
do // While LOOP
{
... Do some process here .....
// Verifies if stop requested
if (!_pauseEvent.WaitOne(0))
{
Console.WriteLine("STOP REQUESTED");
break;
}
}
} while (LOOP);
}
}
}我的问题是:
当我从包含此StopPlaying的表单的一个按钮调用UserControl ()时,线程中所做的测试将正确检测,但是当我从SetText()方法调用StopPlaying时,它就不起作用了,就好像事件没有被重置一样。
顺便说一下,方法SetText()是由同一个表单的另一个按钮调用的。
发布于 2016-06-03 00:16:39
看起来,您的StartText()方法中有一个竞争条件。您可以在一个单独的线程上运行StartText,并且从主UI线程调用SetText(),所以可能发生的情况是,SetText()正在重置,然后在将控制传递回另一个线程之前设置_pauseEvent。因此,就StartText而言,重置从未发生过。
https://stackoverflow.com/questions/37599501
复制相似问题