Windows Mobile 使用 .NET Compact Framework 开发多线程程序
2010-03-10 16:36:00 来源:WEB开发网Instantiate a new Message object and put into the shared container “messageList”. Use lock() function to lock the shared resource and use autoEvent to wake up handler thread. At the same time, display the thread name and the Message information to list control.
请求线程负责申请请求对象(Message)然后把请求放进共享资源(messageList)。访问共享资源的时候通过lock函数来锁定。把请求放进list以后,使用autoEvent 去唤醒处理线程。在此同时把请求信息显示到list控件上。
Handler thread
//Handler threadprivate void HanlderThreadProc(){ while (started) { //Only
one thread at a time can enter.Wait until it is safe to enter.
autoEvent.WaitOne(); if (!started) { //If the the thread should be quit, return
immediately. return; } //Use temp list to decrease the lock duration.
List
Handler thread would be in sleep until get the wake up event. Use lock() function to lock the shared resource and use temporary list to store the requests to reduce the lock duration. When process the request, only display the thread name and the Message information to list control. Usually, I would like to use polymorphism. Use different request handle function in derided classes which have the same interface (Template Methods pattern).
处理线程会一直sleep直到得到唤醒消息。访问共享资源的时候同样适用lock函数加锁。为了减少锁的时间,我偏向于使用临时容器把所有请求先缓存下来,在这个例子中,仅仅把请求信息打印到list控件,在实际运用中,我通常通过多态的方法,使用Template Methods模式来处理请求。
更多精彩
赞助商链接