Blond Mobile


Windows Mobile, C#: How to stop a thread after calling CeRunAppAtEvent / WaitForSingleObject

In a previous post, I wrote about how to run a method when the device wakes up, or comes back from sleep mode. In that post I wrote about calling the CeRunAppAtEvent native function, which signals a given  event (hEvent) when the device wakes up.  I used the WaitForSingleObject(hEvent, INFINITE) function to wait until the hEvent is signaled.

The problem occurs when wanting to close the application, and a thread, which called the WaitForSingleObject()  is still waiting for the event. In that post, I wrote that in case wanting to close the application the below function should be called in order to terminate the waiting thread.

public static void Close()
{
    _close = true;
    if(_wakeupServiceThread != null)
       _wakeupServiceThread.Abort();
}

Unfortunately, The wakeupServiceThread could not be aborted, since it was waiting due to the call to WaitForSingleObject function.

The solution was to stop waiting on the WaitForSingleObject function,  and for that the _nativeWakupEvent event needed to be signaled.

Here is the code:

[DllImport("coredll.dll", SetLastError = true)]
        public static extern bool EventModify(IntPtr hEvent,
            [In, MarshalAs(UnmanagedType.U4)] int dEvent);
private const int NATIVE_EVENT_SET = 3;

public static void Close()
{
     _close = true;
     if (_hEvent != IntPtr.Zero)
             SetEvent(_hEvent);
}
private static bool SetEvent(IntPtr hEvent)
{
     return EventModify(hEvent, NATIVE_EVENT_SET);
}

Tags: , , , , ,

3 Responses to “Windows Mobile, C#: How to stop a thread after calling CeRunAppAtEvent / WaitForSingleObject”

  1. Arjan Says:

    Hi, this code is very useful, I only can’t figure out to what the _hEvent and the _close refers to in your original code down below. Thanks in advance.

  2. jasmine Says:

    The post has moved to http://www.blondmobile.com/2008/04/windows-mobile-c-how-to-stop-thread.html

  3. Jasmine Says:

    This post has moved to http://www.blondmobile.com/2008/04/windows-mobile-c-how-to-stop-thread.html

    please write all comments in the new location

    Thanks

Leave a Reply

Jajah is the VoIP player that brought you web-activated telephony.