Na poniższym przykładzie można zaobserwować różnicę przy obu przypadkach.
namespace ThreadStaticAttribute { public class MyClass { [System.ThreadStatic] public static int Count; public static int Count2; public void Count10() { for (int i = 0; i < 10; i++) { Count++; Count2++; } } public void Count20() { for (int i = 0; i < 20; i++) { Count++; Count2++; } } } }
using System; using System.Threading; namespace ThreadStaticAttribute { class Program { static void Main(string[] args) { var c1 = new MyClass(); Thread t1 = new Thread(new ThreadStart(c1.Count10)); Thread t2 = new Thread(new ThreadStart(c1.Count20)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); MyClass.Count++; MyClass.Count2++; Console.WriteLine(MyClass.Count); Console.WriteLine(MyClass.Count2); Console.ReadLine(); } } }
Zgodnie z przewidywaniami, konsola wyświetli wynik, jak poniżej.
1 31
Brak komentarzy:
Prześlij komentarz