C#的线程问题

zhaoshiwu 2010-01-11 09:27:36
记得再看一段线程代码的时候
发现一个这样的东西.
[ThreadStatic]
这个是干嘛用的啊
...全文
68 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hitlcyu19 2010-01-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 newegg2009 的回复:]
//标记为 ThreadStaticAttribute 的静态字段不在线程之间共享。
  // 可以测试以下的实例有助于理解
class Program
  {
    [ThreadStatic]
    static int i;
    static Random r = new Random();

    public static void ThreadProc()
    {
      i = r.Next(1, 10);

      while (true)
      {
        Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, i);
        Thread.Sleep(500);
      }
    }

    public static void Main()
    {
      for (int i = 0; i < 2; i++)
      {
        Thread t = new Thread(new ThreadStart(ThreadProc));
        t.Name = "T" + i.ToString();
        t.Start();
      }

      Console.WriteLine("Press Enter key to exit...");
      Console.ReadLine();
    }
  }

[/Quote]
sunchen891229 2010-01-11
  • 打赏
  • 举报
回复
路过,学习了~
  • 打赏
  • 举报
回复
//标记为 ThreadStaticAttribute 的静态字段不在线程之间共享。
// 可以测试以下的实例有助于理解
class Program
{
[ThreadStatic]
static int i;
static Random r = new Random();

public static void ThreadProc()
{
i = r.Next(1, 10);

while (true)
{
Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, i);
Thread.Sleep(500);
}
}

public static void Main()
{
for (int i = 0; i < 2; i++)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Name = "T" + i.ToString();
t.Start();
}

Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
}

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧