这里利用线程池和匿名方法,把UI事件处理Wire Up到后台线程处理。详见下面的程序:
首先,定义一个UI事件,这个事件将在后台线程上被触发,后台处理例程将订阅这个事件。
public delegate void UIPressedEventHandler(object sender, UIEventArgs e);
public event UIPressedEventHandler UIEventRaised;
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
}
{
#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);
}
{
if (UIEventRaised != null) UIEventRaised(sender, e);
}
这个例程将在后台线程上运行。
几点说明:
1、宏符号UIThread用于在需要跟踪调试时Bypass后台线程,以便能够Step Into。
2、注解部分是用新线程来Wire Up事件。
3、delegate用于引出一个匿名方法。
4、好处:简单明了。