文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>ASP.NET----线程数据插槽

ASP.NET----线程数据插槽

时间:2011-06-06  来源:brainmao

using System;
using System.Threading;

namespace NET.MST.Seventh.ThreadDataSlot
{
class MainClass
{
/// <summary>
/// 测试数据插槽
/// </summary>
static void Main()
{
Console.WriteLine(
"现在开始测试数据插槽");
//开辟五个线程来同时运行
//这里不适合用线程池,
//因为线程池内的线程会被反复使用
//导致线程ID一致
for (int i = 0; i < 5; i++)
{
Thread thread
=
new Thread(ThreadDataSlot.Work);
thread.Start();
}
Console.Read();
}
}

/// <summary>
/// 包含线程方法和数据插槽
/// </summary>
class ThreadDataSlot
{
//分配一个数据插槽,注意插槽本身是全局可见的,
//因为这里的分配是在所有线程的TLS内建立数据块
static LocalDataStoreSlot _localSlot =
Thread.AllocateDataSlot();

/// <summary>
/// 线程方法,操作数据插槽来存放数据
/// </summary>
public static void Work()
{
// 这里把线程ID存放在数据插槽内
// 一个应用程序内线程ID不会重复
Thread.SetData(_localSlot,
Thread.CurrentThread.ManagedThreadId);

// 查看一下刚刚插入的数据
Console.WriteLine("线程{0}内的数据是:{1}",
Thread.CurrentThread.ManagedThreadId.ToString(),
Thread.GetData(_localSlot).ToString());

// 这里线程睡眠1秒
Thread.Sleep(1000);

//查看其它线程的运行是否干扰了当前线程数据插槽内的数据
Console.WriteLine("线程{0}内的数据是:{1}",
Thread.CurrentThread.ManagedThreadId.ToString(),
Thread.GetData(_localSlot).ToString());
}
}
}
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载