Search code examples
c#windowsmultithreadingclrmd

Calling WaitForSingleObject from C#


I am trying to call WaitForSingleObject method from C#, as documented here:

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

In order to call this function I need to create a Handle, or I need to get a Handle of type IntPtr, how can it be done?

I've tried this function that I found: 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);

Or for instance, when I am getting handle from console:

IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;

It throws a DllNotFoundException.

What's the issue here?

I need it in order to run the process with this function call, and to take a dump form its process, for my ClrMd library learning.

Any help will be appreciated.

Code sample:

  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;

Solution

  • I want to call native method (WaitForMultipleObjects) which waits for some handle (don't really mind which one), then I want to see it on thread stack using ClrMd library, from dump file

    OK, so what about new ManualResetEvent(false).WaitOne()? This should show up in the dump file. And it's reliable.

    Just picking any existing handle is not reliable because it might be signaled or be destroyed at any time. Or, you might change its state by waiting. There is no need, a ManualResetEvent can create you a fresh handle.