Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

CreateEvent (coredll)
 

coredll is for smart devices, not desktop Windows. Therefore, this information only applies to code using the .NET Compact Framework. To see if information for CreateEvent in other DLLs exists, click on Find References to the right.

.
Summary
Creates a new event handler.

C# Signature:

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

VB Signature:

Declare Function CreateEvent Lib "coredll.dll" (ByVal lpEventAttributes As IntPtr, ByVal bManualReset As Boolean, ByVal bInitialStatre As Boolean, ByVal lpName As String) As IntPtr

Declare Function CreateEvent Lib "coredll.dll" (ByVal lpEventAttributes As IntPtr, ByVal bManualReset As Boolean, ByVal bInitialStatre As Boolean, ByVal lpName As String) As IntPtr

User-Defined Types:

None.

Alternative Managed API:

Do you know one? Please contribute it!

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using HANDLE = System.IntPtr;

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

        [DllImport("coredll.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(HANDLE hObject);

        static void Main(string[] args)
        {
            HANDLE p = CreateEvent(HANDLE.Zero, false, true, null);

            CloseHandle(p);
        }
    }
}

VB.NET Sample Wrapper:

    Imports System.Runtime.InteropServices

    Public Class WaitHandles

    Public Enum EventFlags As Integer
        PULSE = 1
        RESET = 2
        [SET] = 3
    End Enum

    <DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=False)> _
    Public Shared Function WaitForMultipleObjects(ByVal count As Integer, ByVal handle() As IntPtr, ByVal waitAll As Boolean, ByVal milliseconds As Integer) As Integer
    End Function

    <DllImport("coredll.dll", SetLastError:=True)> _
    Public Shared Function WaitForSingleObject(ByVal handle As IntPtr, ByVal milliseconds As Integer) As Integer
    End Function

    <DllImport("coredll.dll", CharSet:=CharSet.Unicode, SetLastError:=False)> _
    Public Shared Function CloseHandle(ByVal handle As IntPtr) As Boolean
    End Function

    <DllImport("coredll.dll", CharSet:=CharSet.Auto, SetLastError:=False, CallingConvention:=CallingConvention.Winapi)> _
    Public Shared Function CreateEvent(ByVal eventAttributes As IntPtr, <MarshalAs(UnmanagedType.Bool)> ByVal isManualReset As Boolean, <MarshalAs(UnmanagedType.Bool)> ByVal initialState As Boolean, <MarshalAs(UnmanagedType.BStr)> ByVal eventName As String) As IntPtr
    End Function

    <DllImport("coredll.dll", SetLastError:=False)> _
    Public Shared Function EventModify(ByVal handle As IntPtr, ByVal eventAction As Integer) As Integer
    End Function

    Public Shared Function SetEvent(ByVal handle As IntPtr) As Integer
        Return EventModify(handle, EventFlags.SET)
    End Function

    Public Shared Function ResetEvent(ByVal handle As IntPtr) As Integer
        Return EventModify(handle, EventFlags.RESET)
    End Function
    End Class

    Public MustInherit Class WaitEventException
    Inherits System.Exception

    Sub New(ByVal message As String, ByVal innerException As Exception)
        MyBase.New(message, innerException)
    End Sub
    End Class

    ''' <summary>
    ''' The exception that is thrown when one thread acquires a Mutex object that another thread has abandoned by exiting without releasing it.
    ''' </summary>
    ''' <remarks>When a thread abandons a mutex, the exception is thrown in the next thread that acquires the mutex. The thread might acquire the mutex because it was already waiting on the mutex or because it enters the mutex at a later time.
    '''
    '''An abandoned mutex indicates a serious programming error. When a thread exits without releasing the mutex, the data structures protected by the mutex might not be in a consistent state. Prior to version 2.0 of the .NET Framework, such problems were hard to discover because no exception was thrown if a wait completed as the result of an abandoned mutex. For more information, see the Mutex class.
    '''
    '''The next thread to request ownership of the mutex can handle this exception and proceed, provided that the integrity of the data structures can be verified.</remarks>
    Public Class WaitEventAbandondException
    Inherits WaitEventException

    Sub New(ByVal message As String)
        MyBase.New(message, Nothing)
    End Sub

    Sub New(ByVal message As String, ByVal innerException As Exception)
        MyBase.New(message, innerException)
    End Sub

    End Class

    ''' <summary>
    ''' This class contains a custom implementation of the WaitHandles for .NET compact framework
    ''' </summary>
    ''' <remarks></remarks>
    Public MustInherit Class WaitEvent
    Implements IDisposable

    Public Const Infitite As Integer = -1
    Public Const WaitAbandond As Integer = &H80I
    Public Const WaitObject0 As Integer = &H0I
    Public Const WaitTimeout As Integer = &H102I

    Private _handle As IntPtr = IntPtr.Zero

    ''' <summary>
    ''' Initialise a new event
    ''' </summary>
    ''' <param name="initialState">true to set the initial state to signaled; false to set the initial state to non-signaled</param>
    ''' <remarks></remarks>
    Sub New(ByVal initialState As Boolean, ByVal name As String, ByVal isManualResetEvent As Boolean)
        _handle = WaitHandles.CreateEvent(IntPtr.Zero, isManualResetEvent, initialState, name)
    End Sub

    ''' <summary>
    ''' Gets the pointer to the WaitHandle
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property WaitHandle() As IntPtr
        Get
        Return _handle
        End Get
    End Property

    ''' <summary>
    ''' Waits for any of the elements in the specified array to receive a signal, using a 32-bit signed integer to specify the time interval.
    ''' </summary>
    ''' <param name="waitHandles">A WaitHandle array containing the objects for which the current instance will wait.</param>
    ''' <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely. </param>
    ''' <returns>index of the waithandle; or -1 for failure; or WaitTimeout for timeout exceeded</returns>
    ''' <exception cref="WaitEventAbandondException">Raised if the platform abandonds the wait event due to closing or disposing by another thread</exception>
    ''' <remarks></remarks>
    Public Shared Function WaitAny(ByRef waitHandles() As WaitEvent, Optional ByVal millisecondsTimeout As Integer = Infitite) As Integer
        Return Wait(waitHandles, False, millisecondsTimeout)
    End Function

    ''' <summary>
    ''' Waits for all the elements in the specified array to receive a signal, using an Int32 value to specify the time interval.
    ''' </summary>
    ''' <param name="waitHandles">A WaitEvent array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates). </param>
    ''' <param name="millisecondsTimeout">The number of milliseconds to wait, or WaitEvent.Infinite (-1) to wait indefinitely. </param>
    ''' <returns>-1 for failure; or WaitTimeout for timeout exceeded; otherwise success</returns>
    ''' <remarks></remarks>
    ''' <exception cref="WaitEventAbandondException">Raised if the platform abandonds the wait event due to closing or disposing by another thread</exception>
    Public Shared Function WaitAll(ByRef waitHandles() As WaitEvent, Optional ByVal millisecondsTimeout As Integer = Infitite) As Integer
        Return Wait(waitHandles, True, millisecondsTimeout)
    End Function

    ''' <summary>
    ''' Performs the wait functions
    ''' </summary>
    ''' <param name="waitEvents"></param>
    ''' <param name="waitAll"></param>
    ''' <param name="millisecondsTimeout"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function Wait(ByRef waitEvents() As WaitEvent, ByVal waitAll As Boolean, ByVal millisecondsTimeout As Integer) As Integer
        If waitEvents Is Nothing Then
        Throw New ArgumentNullException("waitHandles", "The waitHandles parameter is Nothing")
        ElseIf waitEvents.Length = 0 Then
        Throw New ArgumentException("Must specify one or more WaitEvents", "waitEvents")
        ElseIf Not Array.TrueForAll(waitEvents, Function(hand As WaitEvent) hand IsNot Nothing) Then
        Throw New ArgumentNullException("waitHandles", "One or more of the objects in the waitHandles array is Nothing")
        ElseIf Not Array.TrueForAll(waitEvents, Function(hand As WaitEvent) hand._handle <> IntPtr.Zero) Then
        Throw New ArgumentException("One or more of the waithandle objects contains an un-initialized handle", "waitHandles")
        End If

        ' Generate a one-dimension array of IntPtr for passing to coredll.dll
        Dim handlePointers(waitEvents.Length - 1) As IntPtr
        For i As Integer = 0 To waitEvents.Length - 1
        handlePointers(i) = waitEvents(i).WaitHandle
        Next

        ' Perform the waiting
        Dim val As Integer = WaitHandles.WaitForMultipleObjects(waitEvents.Length, handlePointers, waitAll, millisecondsTimeout)

        Select Case val
        Case WaitAbandond
            Throw New WaitEventAbandondException("Wait event was abandond by coredll.dll")

            Return -1
        Case Else
            Return val
        End Select
    End Function

    ''' <summary>
    ''' Blocks the current thread until the current WaitHandle receives a signal.
    ''' </summary>
    ''' <param name="millisecondsTimeout"></param>
    ''' <returns>-1 for failure; or WaitTimeout for timeout exceeded; otherwise success</returns>
    ''' <remarks></remarks>
    ''' ''' <exception cref="WaitEventAbandondException">Raised if the platform abandonds the wait event due to closing or disposing by another thread</exception>
    Public Function WaitOne(Optional ByVal millisecondsTimeout As Integer = -1) As Integer
        If _handle = IntPtr.Zero Then
        Throw New ObjectDisposedException("WaitHandle", "WaitEvent has already been closed or never initialized")

        Return -1
        Else

        Dim val As Integer = WaitHandles.WaitForSingleObject(Me._handle, millisecondsTimeout)

        Select Case val
            Case WaitAbandond
            Throw New WaitEventAbandondException("Wait event was abandond by coredll.dll")

            Return -1
            Case Else
            Return val
        End Select
        End If
    End Function

    ''' <summary>
    ''' Releases all resources held by the current WaitEvent.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Close() As Boolean
        If _handle = IntPtr.Zero Then
        Throw New ObjectDisposedException("WaitHandle", "WaitEvent has already been closed or never initialized")

        Return False
        Else
        WaitHandles.CloseHandle(_handle)
        _handle = IntPtr.Zero

        Return True
        End If
    End Function

    ''' <summary>
    ''' Sets the state of the event to signaled, allowing one or more waiting threads to proceed.
    ''' </summary>
    ''' <remarks>The state of a manual-reset event object remains signaled until it is set explicitly to the nonsignaled state by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object by calling one of the wait functions, can be released while the object's state is signaled.
    '''
    '''The state of an auto-reset event object remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.
    '''
    '''Each object type, such as memory maps, semaphores, events, message queues, mutexes, and watchdog timers, has its own separate namespace. Empty strings, "", are handled as named objects. On Windows desktop-based platforms, synchronization objects all share the same namespace.</remarks>
    ''' <returns>Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.</returns>
    Public Function [Set]() As Boolean
        Return WaitHandles.SetEvent(Me._handle)
    End Function

    ''' <summary>
    ''' Sets the state of the event to nonsignaled, causing threads to block.
    ''' </summary>
    ''' <returns>Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.</returns>
    ''' <remarks>ResetEvent returns FALSE if the handle to the event object is invalid.
    '''
    '''The state of an event object remains nonsignaled until it is explicitly set to signaled by the SetEvent or PulseEvent function. This nonsignaled state blocks the execution of any threads that have specified the event object in a call to one of the wait functions.
    '''
    '''ResetEvent sets the event to the nonsignaled state even if the event was signaled multiple times before being signaled. The ResetEvent function is used primarily for manual signal event objects, which must be set explicitly to the nonsignaled state. Auto-signal event objects automatically change from signaled to nonsignaled after a single waiting thread is released.
    '''
    '''Each object type, such as memory maps, semaphores, events, message queues, mutexes, and watchdog timers, has its own separate namespace. Empty strings, "", are handled as named objects. On Windows desktop-based platforms, synchronization objects all share the same namespace.</remarks>
    Public Function Reset() As Boolean
        Return WaitHandles.ResetEvent(Me._handle)
    End Function

    Private disposedValue As Boolean = False    ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
        If disposing Then
            WaitHandles.CloseHandle(Me._handle)
        End If

        End If
        Me.disposedValue = True
    End Sub

    #Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
    #End Region

    End Class

    ''' <summary>
    ''' Wraps a custom type of AutoResetEvent
    ''' </summary>
    ''' <remarks></remarks>
    Public Class AutoResetWaitEvent
    Inherits WaitEvent

    ''' <summary>
    ''' Initialise a new event
    ''' </summary>
    ''' <param name="initialState">true to set the initial state to signaled; false to set the initial state to non-signaled</param>
    ''' <param name="name">name of the event</param>
    ''' <remarks></remarks>
    Sub New(ByVal initialState As Boolean, Optional ByVal name As String = Nothing)
        MyBase.New(initialState, name, False)
    End Sub
    End Class

    ''' <summary>
    ''' Wraps a custom type of ManualResetEvent
    ''' </summary>
    ''' <remarks></remarks>
    Public Class ManualResetWaitEvent
    Inherits WaitEvent

    ''' <summary>
    ''' Initialise a new ManualResetEvent
    ''' </summary>
    ''' <param name="initialState">true to set the initial state to signaled; false to set the initial state to non-signaled</param>
    ''' <param name="name">name of the event</param>
    ''' <remarks></remarks>
    Sub New(ByVal initialState As Boolean, Optional ByVal name As String = Nothing)
        MyBase.New(initialState, name, True)
    End Sub
    End Class

Documentation
CreateEvent on MSDN

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions