My Blog

Using ThreadStatic attribute

by lupok on martedì 23 luglio 2013 11:14
l'attributo ThreadStatic indica che il valore di un campo statico è unico per ciascun thread, di seguito è riportato un esempio che mostra come utilizzare tale attributo e gli effetti esso che provoca.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace UsingThreadStatic
{
   class Program
   {
      [ThreadStatic]
      static Int32 s_count = 0;
 
      static Object s_synchro = new Object();
 
      static void Main(string[] args)
      {
         for (int i = 0; i < 3; i++)
         {
            Thread thread = new Thread(() =>
            {
               while (true)
               {
                  Console.WriteLine("Thread {0}, Count = {1}"Thread.CurrentThread.Name, Interlocked.Increment(ref s_count));
 
                  Thread.Sleep(1000);
               }
            });
 
            thread.Name = i.ToString();
            thread.IsBackground = true;
            thread.Start();
         }
         Console.Write("Press ENTER to close the host");
         Console.ReadLine();
      }
   }
}

 

 

 

Come si può vedere dall'immagine riportata sopra la variabile s_count contiene un valore che è unico per thread, al contrario nell'immagine sotto si vede il risultato dell'applicazione eliminando l'attributo ThreadStatic: 

 

UsingThreadStatic.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags