WEB开发网
开发学院手机开发Windows Mobile 开发 Windows Mobile 使用 .NET Compact Framework 开发... 阅读

Windows Mobile 使用 .NET Compact Framework 开发多线程程序

 2010-03-10 16:36:00 来源:WEB开发网   
核心提示:(lockObj) { messageList.Add(msg); } string s = string.Format("{0} - {1} - {2}", Thread.CurrentThread.Name, msg.ID, msg.MessageBody); UpdateMessageList
(lockObj) { messageList.Add(msg); } string s = string.Format("{0} - {1} - {2}", Thread.CurrentThread.Name, msg.ID, msg.MessageBody); UpdateMessageList(s); autoEvent.Set(); ++i; Thread.Sleep(500); }}

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 tempMessageList = new List(); //lock when try to access shared resource. lock (lockObj) { //Access shared resource, messageList in the case. foreach (Message msg in messageList) { tempMessageList.Add(msg); } //clear up all the request inside the list. messageList.Clear(); } //handle the request now. foreach (Message msg in tempMessageList) { string s = string.Format("{0} - {1} - {2}", Thread.CurrentThread.Name, msg.ID, msg.MessageBody); UpdateMessageList(s); } }}

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模式来处理请求。

源代码

上一页  1 2 

Tags:Windows Mobile 使用

编辑录入:coldstar [复制链接] [打 印]
赞助商链接