.NET Practice  
众所周知,对Windows Form应用程序来说,当用户点击UI界面产生的事件,将在UI线程上执行。
这里利用线程池和匿名方法,把UI事件处理Wire Up到后台线程处理。详见下面的程序:

首先,定义一个UI事件,这个事件将在后台线程上被触发,后台处理例程将订阅这个事件。

public delegate void UIPressedEventHandler(object sender, UIEventArgs e);


public
event UIPressedEventHandler UIEventRaised;

下面这个是主要方法,它被Hook Up到UI事件上(它在UI线程上运行)。

        private void Value_UIEventRaised(object sender, UIEventArgs e)
        
{
#if UIThread            
            OnUIEventRaised(sender, e);
#else
            ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate
                                                              
{
                                                                  OnUIEventRaised(sender, e);
                                                              }
));
            //Thread workerThread = new Thread(delegate()
            
//                                     {
            
//                                         OnUIEventRaised(sender, e);
            
//                                     });
            
//workerThread.Start();
#endif

        }


其中

        protected void OnUIEventRaised(object sender, UIEventArgs e)
        
{
            
if (UIEventRaised != null) UIEventRaised(sender, e);
        }

这个例程将在后台线程上运行。

几点说明:
1、宏符号UIThread用于在需要跟踪调试时Bypass后台线程,以便能够Step Into。
2、注解部分是用新线程来Wire Up事件。
3、delegate用于引出一个匿名方法。
4、好处:简单明了。

posted on 2006-12-23 01:30  Chester  阅读(1859)  评论(2编辑  收藏  举报