Silverlight 使用多執行緒threading
Silverlight 基本上跟我們常用的應用程式一樣,有多執行緒(Threading)的功能,這樣除了可以同時做很多件事外也能改同步改變元件的屬性。在Silverlight當中有完整的Threading的library可以使用,但有很多種方式,例如BackgroundWorker、ThreadPool或是現在這種法式,使得能夠有高效率的作業。
這篇文章主要是參考http://silverlight.net/blogs/msnow/archive/2008/11/25/silverlight-tip-of-the-day-73-threading-in-silverlight.aspx
但我改了一些,讓不同元件都使用Threading情形比較明白的呈現出來,而且這篇文章也順便教了我們如何在App.xaml改變Page.xaml設定值
這就是傳值的方法
private void Application_Exit(object sender, EventArgs e)
{
//在離開程式後更改Page的Done屬性
((Page)this.RootVisual).Done = true;
}這段程式就是讓每個元件在不同的執行緒上,透過這樣的方式,都在執行個體而不會干擾到對方。程式很簡單,一看應該就會懂了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
namespace SilverlightThreadingTest
{
public partial class Page : UserControl
{
//建立static物件
public static Thread tread1, tread2, tread3;
public static int count =0;
public static TextBlock tb1;
public static Rectangle rc1;
public static ProgressBar pb1;
private static bool _done = true;
public bool Done
{
get { return _done; }
set { _done = value; }
}
public Page()
{
InitializeComponent();
tb1 = tb;
rc1 = rt;
pb1 = pb;
}
void StartThread()
{
_done = false;
//TextBlock Threading
tread1 = new Thread(tbThread);
tread1.Start();
//Rectangle Threading
tread2 = new Thread(rcThread);
tread2.Start();
//ProgressBar Threading
tread3 = new Thread(pbThread);
tread3.Start();
}
void tbThread()
{
while (!_done)
{
count++;

tb1.Dispatcher.BeginInvoke(delegate()
{
//顯示count的累加
tb1.Text = count.ToString();
});
//等待一秒
Thread.Sleep(100);
}
}
void rcThread()
{
while (!_done)
{
count++;

rc1.Dispatcher.BeginInvoke(delegate()
{
//變更Rectangle寬度
rc1.Width = count;
});
Thread.Sleep(100);

}
}
void pbThread()
{
while (!_done)
{
count++;

pb1.Dispatcher.BeginInvoke(delegate()
{
//ProgressBar數值
pb1.Value = count/10;
});
Thread.Sleep(100);

}
}
//按下按鈕
private void Button_Click(object sender, RoutedEventArgs e)
{
if (false == _done)
_done = true;
else
this.StartThread();
}
}
}
之後我會再實做不同方法來實做幾個範例吧!!!
