Atomic operations on the C # thread base

Source: Internet
Author: User
Tags sleep thread

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.}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.