简体   繁体   English

如何确定是否在辅助线程中调用了EventWaitHandle.WaitOne

[英]How to determine whether EventWaitHandle.WaitOne was invoked in a secondary thread

I have a main thread which spawns a secondary thread. 我有一个主线程产生一个辅助线程。 This secondary thread is using the EventWaitHandle.WaitOne to wait after performing some particular operation. 此辅助线程在执行某些特定操作后使用EventWaitHandle.WaitOne等待。

Is there any way for the main thread to be signalled when the secondary thread goes to the wait state? 当辅助线程进入等待状态时,有没有办法让主线程发出信号?

I tried using System.Threading.ThreadState property to determine whether the thread is in WaitSleepJoin state when the WaitOne() -method is called, but this approach does not seem to work as the thread always appears to be in Running state. 我尝试使用System.Threading.ThreadState属性来确定WaitOne()方法时线程是否处于WaitSleepJoin状态,但这种方法似乎不起作用,因为线程始终显示处于Running状态。

You can use the second ManualResetEvent to signal main thread: 您可以使用第二个ManualResetEvent来指示主线程:

in the worker thread: 在工作线程中:

signalEWH.Set();

commonEWH.WaitOne();

signalEWM.Reset();

in the main thread 在主线程中

var isWaiting = signalEWH.WaitOne(0);

I have wrote the fololowing test app and it works fine to me 我已经编写了fololowing测试应用程序,它对我来说很好

      class Program
{
    static void Main(string[] args)
    {
        var thr = new Thread(new ThreadStart(SecondThread));
        thr.IsBackground = true;
        thr.Start();

        firstEvent.WaitOne();

        var isSleep = thr.ThreadState.HasFlag(ThreadState.WaitSleepJoin);
    }

    static ManualResetEvent firstEvent = new ManualResetEvent(false);
    static ManualResetEvent secondEvent = new ManualResetEvent(false);

    static void SecondThread()
    {
        firstEvent.Set();
        secondEvent.WaitOne();
        firstEvent.Reset();
    }
}

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

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