首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ManualResetEvent奇怪行为

ManualResetEvent奇怪行为
EN

Stack Overflow用户
提问于 2016-06-02 18:25:47
回答 1查看 100关注 0票数 0

在问之前,我先给出一些代码..。

代码语言:javascript
复制
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()是由同一个表单的另一个按钮调用的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-03 00:16:39

看起来,您的StartText()方法中有一个竞争条件。您可以在一个单独的线程上运行StartText,并且从主UI线程调用SetText(),所以可能发生的情况是,SetText()正在重置,然后在将控制传递回另一个线程之前设置_pauseEvent。因此,就StartText而言,重置从未发生过。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37599501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档