简体   繁体   English

使用ManualResetEvent在内部等待

[英]Wait inside While with ManualResetEvent

I have an operation via While that i want to Freeze: 我通过动手术While ,我要冻结:

    do
    {
        ManualResetEvent.Reset(); // Here i want to wait

        // Here i am doing my stuff...
    }

    while (some boolean value);
}

My ManualResetEvent : 我的ManualResetEvent

private static ManualResetEvent _manualResetEvent;

public static ManualResetEvent ManualResetEvent
{
    get { return _manualResetEvent; }
    set { _manualResetEvent = value; }
}

ManualResetEvent = new ManualResetEvent(false);

In some point in my code via Button i just want to freeze my operation: 在我通过Button代码中,我只是想冻结我的操作:

private void btnPause_Click(object sender, RoutedEventArgs e)
{
    ManualResetEvent.WaitOne();
}

Is this the right way to do that ? 这是正确的方法吗?

You have your two functions backwards. 您有两个功能倒退。 The loop you want to wait needs to use the .WaitOne() . 您要等待的循环需要使用.WaitOne() Also, if you want it to run at the start you need to initialize the reset event to true 另外,如果希望它在开始时运行,则需要将reset事件初始化为true

init 在里面

private static ManualResetEvent _manualResetEvent;

public static ManualResetEvent ManualResetEvent
{
    get { return _manualResetEvent; }
    set { _manualResetEvent = value; }
}

ManualResetEvent = new ManualResetEvent(true); //Set it to true to let it run at the start.

loop

    do
    {
        ManualResetEvent.WaitOne(); // Here i want to wait

        // Here i am doing my stuff...
    }

    while (some boolean value);
}

elsewhere 别处

private void btnPause_Click(object sender, RoutedEventArgs e)
{
    ManualResetEvent.Reset();
}
private void btnUnPause_Click(object sender, RoutedEventArgs e)
{
    ManualResetEvent.Set();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM