从C#调用WaitForSingleObject

我正在尝试从C#中调用WaitForSingleObject方法,如下所述:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx

为了调用这个函数,我需要创build一个Handle,或者我需要得到一个IntPtrtypes的Handle,怎么做?

我试过这个function,我发现: http : //www.pinvoke.net/default.aspx/kernel32.WaitForSingleObject

[DllImport("coredll.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)] public static extern IntPtr CreateEvent(HANDLE lpEventAttributes, [In, MarshalAs(UnmanagedType.Bool)] bool bManualReset, [In, MarshalAs(UnmanagedType.Bool)] bool bIntialState, [In, MarshalAs(UnmanagedType.BStr)] string lpName); 

或者,例如,当我从控制台获取句柄时:

 IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; 

它抛出一个DllNotFoundException。

这里有什么问题?

我需要它来运行这个函数调用的过程,并从它的过程中获取一个转储,用于我的ClrMd库学习。

任何帮助将不胜感激。

代码示例:

  static void Main(string[] args) { var autoEvent = new AutoResetEvent(false); //this is where I get the DllNotFoundException WaitForSingleObject(autoEvent.Handle, WAIT_TIMEOUT ); } [DllImport("kernel32.dll")] static extern uint WaitForMultipleObjects(uint nCount, IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds); public const Int32 WAIT_TIMEOUT = 0x102; 

我想调用等待一些句柄的本地方法(WaitForMultipleObjects)(不介意哪一个),然后我想在线程堆栈上使用ClrMd库在转储文件中看到它

好的,那么new ManualResetEvent(false).WaitOne()呢? 这应该显示在转储文件中。 这是可靠的。

只是选择任何现有的手柄是不可靠的,因为它可能会被发送或随时销毁。 或者,你可以通过等待来改变它的状态。 没有必要,一个ManualResetEvent可以创建一个新的句柄。

我不会通过WinApi从C#中得到这个:你有C#中的EventWaitHandler和其他同步对象,使用它们:

 WaitHandle wh = new EventWaitHandler(); //do whatever you need ... WaitHandler.WaitOne(wh); // equivalent to WaitForSingleObject in WinApi 

如果你确实需要与WinApi互操作,你可以使用wh.SafeWaitHandle

另外我怀疑Process.GetCurrentProcess().MainWindowHandle不能在一个控制台应用程序,根本没有任何窗口

我的错误,我已经发布WaitForMultipleObjects而不是WaitForSingleObject,主要问题是WaitForSingleObject留在DllImport(“coredll.dll”…)我不知道我在哪里找到它,但我没有…

对困惑感到抱歉