csstome 发表于 2013-2-1 11:38:39

c#线程基础之原子操作

使用System.Threading.Interlocked类可以提高线程的安全性,具体资料参考msdn: http://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx 一般情况下,在子线程内使用i++这样的方式访问全局变量的方式是不安全的做法。测试下面的代码,在test1中经过100次number++,number并没有每次从0变为100,而test2则没有问题。
using System;using System.Windows.Forms;namespace WindowsApplication32{    public partial class Form1 : Form    {      public Form1()      {            InitializeComponent();      }      int number = 0;      /// <summary>      /// 普通的变量访问方式      /// </summary>      private void test1()      {            for (int m = 0; m < 10; m++)            {                number++;                System.Threading.Thread.Sleep(100);            }            Console.WriteLine(number);      }      private void button1_Click(object sender, EventArgs e)      {            number = 0;            for (int i = 0; i < 10; i++)            {                new System.Threading.Thread(test1).Start();            }      }      /// <summary>      /// 使用原子的访问方式      /// </summary>      private void test2()      {            for (int m = 0; m < 10; m++)            {                System.Threading.Interlocked.Increment(ref number);                System.Threading.Thread.Sleep(100);            }            Console.WriteLine(number);      }      private void button2_Click(object sender, EventArgs e)      {            number = 0;            for (int i = 0; i < 10; i++)            {                new System.Threading.Thread(test2).Start();            }      }    }}
页: [1]
查看完整版本: c#线程基础之原子操作