参考文章:
http://www.cnblogs.com/xqiwei/archive/2012/02/16/2353870.html
实例说明:
在Windows Phone开发中,使用线程和其他有些不同,线程的使用是和委托结合在一起的。
在MainPage中,只有一个按钮和TextBlock,通过线程实现每隔2秒钟更新一次TextBlock的内容。
代码如下:
public partial class MainPage : PhoneApplicationPage
{
delegate void MyDelegate(); //线程委托
MyDelegate mydelegate = null; //委托实例化
static string temp = ""; //循环过程中更新的变量
// 构造函数
public MainPage()
{
InitializeComponent();
}
/// <summary>
///功能:更新UI
/// </summary>
public void UpdateTextBlock() {
this.textBlock1.Text = "循环次数为===" + temp;
}
/// <summary>
/// 功能:线程,实现每隔一段时间循环一次更新
/// </summary>
public void MyThread()
{
int i = 0;
while (i < 5)
{
temp = i.ToString();
this.Dispatcher.BeginInvoke(mydelegate);
Thread.Sleep(1000 * 2);
i++;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//加载时发生线程
mydelegate = UpdateTextBlock;
Thread tt = new Thread(new ThreadStart(MyThread));
tt.Start();
}
}