Silverlight(26) - 2.0线程之Lock, Interlocked, EventWaitHandle, Monitor, ThreadStaticAttribute
2008-12-31 11:53:44 来源:WEB开发网5、ThreadStaticAttribute.xaml
<UserControl x:Class="Silverlight20.Thread.ThreadStaticAttribute"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel HorizontalAlignment="Left" Margin="5">
<TextBlock x:Name="txtMsg" />
<TextBlock x:Name="txtMsg2" />
</StackPanel>
</UserControl>
ThreadStaticAttribute.xaml.cs
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;
namespace Silverlight20.Thread
{
public partial class ThreadStaticAttribute : UserControl
{
// ThreadStatic - 所指定的静态变量对每个线程都是唯一的
[System.ThreadStatic]
private static int value;
// 一般的静态变量,对每个线程都是共用的
private static int value2;
public ThreadStaticAttribute()
{
InitializeComponent();
Demo();
}
void Demo()
{
System.Threading.Thread thread = new System.Threading.Thread(DoWork);
thread.Name = "线程1";
thread.Start();
System.Threading.Thread.Sleep(100);
System.Threading.Thread thread2 = new System.Threading.Thread(DoWork2);
thread2.Name = "线程2";
thread2.Start();
}
void DoWork()
{
for (int i = 0; i < 10; i++)
{
// 线程1对静态变量的操作
value++;
value2++;
}
string s = value.ToString(); // value - 本线程独有的静态变量
string s2 = value2.ToString(); // value2 - 所有线程共用的静态变量
this.Dispatcher.BeginInvoke(delegate { txtMsg.Text = s + " - " + s2; });
// this.Dispatcher.BeginInvoke(delegate { txtMsg.Text = value + " - " + value2; }); // 在UI线程上调用,所以value值为UI线程上的value值,即 0
}
void DoWork2()
{
for (int i = 0; i < 10; i++)
{
// 线程2对静态变量的操作
value++;
value2++;
}
string s = value.ToString(); // value - 本线程独有的静态变量
string s2 = value2.ToString(); // value2 - 所有线程共用的静态变量
this.Dispatcher.BeginInvoke(delegate { txtMsg2.Text = s + " - " + s2; });
// this.Dispatcher.BeginInvoke(delegate { txtMsg2.Text = value + " - " + value2; }); // 在UI线程上调用,所以value值为UI线程上的value值,即 0
}
}
}
Tags:Silverlight 线程 Lock
编辑录入:爽爽 [复制链接] [打 印]- ››silverlight全屏显示图片
- ››Silverlight MVVM 模式(一) 切近实战
- ››Silverlight for Windows Phone 7开发系列(1):...
- ››Silverlight for Windows Phone 7开发系列(2):...
- ››Silverlight for Windows Phone 7开发系列(3):...
- ››Silverlight for Windows Phone 7开发系列(4):...
- ››Silverlight for Symbian
- ››Silverlight3系列(四)数据绑定 Data Binding 1
- ››线程状态图
- ››silverlight2 游戏 1 你能坚持多少秒
- ››Silverlight开发实践--PicZoomShow
- ››Silverlight自定义控件开发 - 令人懊恼的OnApplyT...
- 中查找“Silverlight(26) - 2.0线程之Lock, Interlocked, EventWaitHandle, Monitor, ThreadStaticAttribute”更多相关内容
- 中查找“Silverlight(26) - 2.0线程之Lock, Interlocked, EventWaitHandle, Monitor, ThreadStaticAttribute”更多相关内容
- 上一篇:Dreamweaver构建Blog全程实录(10):事件日历
- 下一篇:Silverlight(25) - 2.0线程之Thread, Timer, BackgroundWorker, ThreadPool
更多精彩
赞助商链接