【IT168 专稿】在上篇文章中,我们介绍了Silverlight 4编程环境下的五种多线程编程技巧。在本篇中,我们将介绍另外四种Silverlight 4多线程编程中的支持技术。
1.使用WaitHandle
等待句柄应当是你进行多线程编程的必备装备。由于我们的主要兴趣点在于Silverlight多线程编程相关的内容,所以我们不想再深入探讨WaitHandle。但在此为你提供一个典型的例子,告诉你使用WaitHandle的基本方法。
清单1:
public partial class MainPage : UserControl
{
AutoResetEvent handle = new AutoResetEvent(true);
public MainPage()
{
InitializeComponent();
new Thread(() =>
{
while (true)
{
handle.WaitOne();
this.Dispatcher.BeginInvoke(() =>
{
this.TextBlock1.Text = DateTime.Now.ToString();
});
}
}).Start();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
handle.Set();
}
}
{
AutoResetEvent handle = new AutoResetEvent(true);
public MainPage()
{
InitializeComponent();
new Thread(() =>
{
while (true)
{
handle.WaitOne();
this.Dispatcher.BeginInvoke(() =>
{
this.TextBlock1.Text = DateTime.Now.ToString();
});
}
}).Start();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
handle.Set();
}
}
2.使用定时器
System.Thread.Timer是一个多线程的计时器。这是一个简单的轻量级的计时器,使用回调方法,并由线程池中线程提供相应的服务。让我们看一个相关的例子:
清单2:(参考示例页面TimerTestPage.xaml)
namespace SilverlightMultiThread
{
public partial class TimerTestPage : Page
{
System.Threading.SynchronizationContext _syncContext;
System.Threading.Timer _timer;
private int _flag = 0;
public TimerTestPage()
{
{
public partial class TimerTestPage : Page
{
System.Threading.SynchronizationContext _syncContext;
System.Threading.Timer _timer;
private int _flag = 0;
public TimerTestPage()
{