ThreadStatic特性標記靜態欄位對多線程執行的影響

來源:互聯網
上載者:User
文章目錄
  • ThreadStaticAttribute
  • 範例程式碼
  • 運行結果
  • 分析

類的靜態欄位在類的執行個體中是共用的。多個線程修改執行個體欄位的值在對其它線程來說是可見的,這也是clr預設的行為。對靜態欄位添加ThreadStaticAttribute標記可以改變這種預設的行為。

ThreadStaticAttribute

指示靜態欄位的值對於每個線程都是唯一的。用 ThreadStaticAttribute 標記的 static 欄位不線上程之間共用。每個執行線程都有單獨的欄位執行個體,並且獨立地設定及擷取該欄位的值。如果在不同的線程中訪問該欄位,則該欄位將包含不同的值。

範例程式碼

 

代碼

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace NetThreading

{

/// <summary>

/// 測試一般靜態欄位與有ThreadStatic 標記的靜態欄位在

/// 多線程執行中的區別

/// </summary>

public class TheadStaticAttributeApp:IMain

{

#region IMain 成員

public void MainRun()

{

MyStaticFiledClass myStaticTest = new MyStaticFiledClass();

ThreadStart ts1 = new ThreadStart(myStaticTest.AddXY);

Thread t1 = new Thread(ts1);

Thread t2 = new Thread(ts1);

t1.Start();

t2.Start();

}

#endregion

}

/// <summary>

/// MyStaticTest

/// </summary>

class MyStaticFiledClass

{

/// <summary>

/// 一般靜態變數

/// </summary>

static int X=0;

/// <summary>

/// 有ThreadStatic標記的靜態變數

/// </summary>

[ThreadStatic]

static int threadStaticX=0;

/// <summary>

/// 分別對x,y 自增

/// </summary>

public void AddXY()

{

for (int i = 0; i < 10; i++)

{

X++;

threadStaticX++;

Thread current = Thread.CurrentThread;

string info = string.Format("threadID:{0} x={1}; [ThreadStatic]threadStaticX={2}", current.ManagedThreadId, X, threadStaticX);

Console.WriteLine(info);

Thread.Sleep(500);

}

}

}

}

 

 

運行結果

分析

具有ThreadStatic標記的靜態變數,在每個線程中都有自己的副本。

一般靜態變數測試在進程之間共用的。t1線程中對X的修改與t2線程

對X的修改會累積,所以x的值會是20。而對於threadStaticX來說t1

與t2都是各自擁有的threadStaticX副本,所以threadStaticX的值為

10.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.