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()
{
{
InitializeComponent();
//UI线程
_syncContext = System.Threading.SynchronizationContext.Current;
//输出当前时间
txtMsg.Text = DateTime.Now.ToString() + "/r/n";
_timer = new System.Threading.Timer(MyTimerCallback, "helltimer", 3000, 1000);
}
private void MyTimerCallback(object state)
{
string result = string.Format("{0} - {1}: /r/n", DateTime.Now.ToString(), (string)state);
_syncContext.Post(delegate { txtMsg.Text += result; }, null);
_flag++;
if (_flag == 5)
_timer.Change(5000, 500);
else if (_flag == 10)
_timer.Dispose();
}
}
}