【IT168 专稿】Silverlight是微软重要的RIA工具,可以广泛应用于网络应用开发领域和桌面领域。事实上,自Silverlight for Windows Phone 7登台以来,Silverlight已经吸引了越来越多的开发者。与其直接的竞争对手Flash一样,Silverlight自第一个版本问世以来,已为多线程计算提供广泛而丰富的支持。整体而言,在Silverlight中引入多线程的根本动机主要是为了解决用户体验中的响应速度,进而减少单线程带来的阻塞问题。
在本系列文章中,我想尽可能详细地总结Silverlight 4对于多线程编程技术的支持。其中提供的相关示例代码供读者朋友参考,并欢迎到我的博客(http://space.itpub.net/14466241/)处一起作更深入的探讨。
1.使用Thread类
Thread类是在Silverlight中你首先应该了解的多线程编程工具。在Thread类中定义了许多成员。因为这个类也是C#编程的第一个必须;所以,在此我们不一一列举,而仅用一个具体的例子,说明这个类的基本用法。
清单1:
public partial class ThreadTestPage : Page
{
string result = "";
public ThreadTestPage()
{
InitializeComponent();
ThreadTestMethod();
}
private void ThreadTestMethod()
{
System.Threading.Thread thread = new System.Threading.Thread(DoWork);
thread.Name = "ThreadDemo";
thread.IsBackground = true;
thread.Start(1000);
result += thread.IsAlive + "\r\n";
result += thread.ManagedThreadId + "\r\n";
result += thread.Name + "\r\n";
result += thread.ThreadState + "\r\n";
if (thread.Join(5000))
{
result += "The specified thread has terminated within 5 seconds.\r\n";
}
{
string result = "";
public ThreadTestPage()
{
InitializeComponent();
ThreadTestMethod();
}
private void ThreadTestMethod()
{
System.Threading.Thread thread = new System.Threading.Thread(DoWork);
thread.Name = "ThreadDemo";
thread.IsBackground = true;
thread.Start(1000);
result += thread.IsAlive + "\r\n";
result += thread.ManagedThreadId + "\r\n";
result += thread.Name + "\r\n";
result += thread.ThreadState + "\r\n";
if (thread.Join(5000))
{
result += "The specified thread has terminated within 5 seconds.\r\n";
}