Using the System.Threading.Interlocked class can improve thread security, specific reference msdn:http://msdn.microsoft.com/zh-cn/library/ System.threading.interlocked.aspx in general, it is unsafe to access global variables in a child thread in such a manner as i++. Test the following code, after 100 times in the Test1 Number++,number does not change from 0 to 100 each time, and test2 is no problem.
01.using System;
02.
03.using System.Windows.Forms;
04.
05.namespace WindowsApplication32
06.
07.{
08.
public partial class Form1:form
10.
11. {
12.
Public Form1 ()
14.
15. {
16.
InitializeComponent ();
18.
19.}
20.
int number = 0;
22.
23.
24.
///<summary>
26.
27.///Ordinary variable access mode
28.
///</summary>
30.
private void Test1 ()
32.
33. {
34.
for (int m = 0; m < m++)
36.
37. {
38.
number++;
40.
System.Threading.Thread.Sleep (100);
42.
43.}
44.
Console.WriteLine (number);
46.
47.}
48.
private void Button1_Click (object sender, EventArgs e)
50.
51. {
52.
Number = 0;
54.
for (int i = 0; i < i++)
56.
57. {
58.
New System.Threading.Thread (test1). Start ();
60.
61.}
32K
63.}
64.
///<summary>
66.
67.///use of atomic access mode
68.
///</summary>
70.
private void Test2 ()
72.
73. {
74.
for (int m = 0 M < m++)
76.
77. {
78.
System.Threading.Interlocked.Increment (ref number);
80.
Bayi. System.Threading.Thread.Sleep (100);
82.
83.}
84.
Console.WriteLine (number);
86.
87.}
88.
The private void button2_click (object sender, EventArgs e)
90.
91. {
92.
Number = 0;
94.
for (int i = 0; i < i++)
96.
97. {
98.
New System.Threading.Thread (TEST2). Start ();
100.
101.}
102.
103.}
104.
105.}
106.
107.}