Three ways for safe threading:
1
2 using System;
3 using System.Collections.Generic;
4 using System.Text;
5 using System.Threading;
6
7 namespace ConsoleApplication12
8 {
9 class Program
10 {
11 static object thisLock = new object();
12 static int z = 0;
13 private static void ThrStart()
14 {
15 for (int i = 0; i < 10000; i++)
16 {
17 lock (thisLock)
18 {
19 z++;
20 Console.WriteLine(z);
21 }
22 }
23 }
24
25 private static void ThrStart2()
26 {
27 for (int i = 0; i < 10000; i++)
28 {
29 Monitor.Enter(thisLock);
30 z++;
31 Console.WriteLine(z);
32 Monitor.Exit(thisLock);
33 }
34 }
35
36 static Mutex mutex = new Mutex();
37 private static void ThrStart3()
38 {
39 for (int i = 0; i < 10000; i++)
40 {
41 mutex.WaitOne();
42 z++;
43 Console.WriteLine(z);
44 mutex.ReleaseMutex();
45 }
46 }
47
48
49 static void Main(string[] args)
50 {
51 Thread t1 = new Thread(new ThreadStart(ThrStart));
52 Thread t2 = new Thread(new ThreadStart(ThrStart));
53 t1.Start();
54 t2.Start();
55 t1.Join();
56 t2.Join();
57
58 t1 = new Thread(new ThreadStart(ThrStart2));
59 t2 = new Thread(new ThreadStart(ThrStart2));
60 t1.Start();
61 t2.Start();
62 t1.Join();
63 t2.Join();
64
65 t1 = new Thread(new ThreadStart(ThrStart3));
66 t2 = new Thread(new ThreadStart(ThrStart3));
67 t1.Start();
68 t2.Start();
69 t1.Join();
70 t2.Join();
71 }
72 }
73 }
74