本文介绍了从C#调用WaitForSingleObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试从C#调用WaitForSingleObject方法,如此处所述:

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

要调用此函数,我需要创建一个Handle,或者需要获取IntPtr类型的Handle,该怎么做?

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?

我尝试了以下发现的功能: http://www.pinvoke.net/default.aspx/kernel32.WaitForSingleObject

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;

它抛出DllNotFoundException.

It throws a DllNotFoundException.

这是什么问题?

我需要它以便通过此函数调用运行该过程,并从其过程中进行转储,以进行我的ClrMd库学习.

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.

任何帮助将不胜感激.

代码示例:

  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;

推荐答案

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

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

仅选择任何现有手柄是不可靠的,因为它随时可能发出信号或被破坏.或者,您可以通过等待更改其状态.不需要,ManualResetEvent可以为您创建新的句柄.

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.

这篇关于从C#调用WaitForSingleObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:57