In WinCE or Windows Moblie development, a large amount of batch processing work is often submitted to the Worker Thread. When the batch processing is completed, or when the process fails or is abnormal, You need to notify the interface process (UI Thread) for synchronization. (PS: Sometimes two worker threads are synchronized, not the UI thread, which is determined by the specific application .) At this time, you often need to wait for the event.
The wait events provided by. NET Framework are encapsulated in System. Threading. WaitHandle. However, WaitHandle In the. NET Compact Framework does not provide all. NET Framework functions. WaitOne is provided only during the waiting time (only one Event can be waited ). In fact, in general applications, the UI process often waits for an event. The following shows how to use WaitOne.
WaitHandle is an abstract class, so the example uses its sub-class AutoResetEvent.
// Define the field, which must be accessed by both the parent thread and child thread.
Private static AutoResetEvent autoEvent = new AutoResetEvent (false );
Public bool Connect ()
{
// Do something. eg make connections.
ThreadPool. QueueUserWorkItem (
New WaitCallback (CheckConnection), null );
// Wait for work method to signal.
If (autoEvent. WaitOne (5000, false ))
{
Return true;
}
Else
{
Return false;
}
}
Private void CheckConnection (Object stateInfo)
{
While (true)
{
If (CheckConnection ())
{
// Signal that work is finished.
AutoEvent. Set ();
}
}
}
Define an AutoResetEvent object, which is used by both the parent process and child process. WaitOne () is used in the parent process. The first parameter is the waiting time. If it is-1, it indicates that it is always waiting and does not return.
Set () is used in subthreads. After batch processing is complete, you can call Set () to notify the parent process.
WaitHandle is widely used. For example, it can be used to listen to data sources in a service program, process data when there is data, and wait for timeout time when there is no data to process regular. This also plays a role in sleep.
While (true)
{
If (autoEvent. WaitOne (5000, false ))
{
ProcReques ();
}
Else
{
ProcRegularTask ();
}
}
If it is not enough to wait for a single event, you can only use the Win32 API WaitForMultipleObjects. P/Invoke is required.
References
. NET Framework WaitHandle Members
. NET Compact Framework, WinCE, Windows Mobile Development Series
Jake's Blog in Blog Park-simplified development of wireless life