您的位置:首页 > 编程语言 > C#

c#线程基础之原子操作

2008-06-20 13:57 295 查看
使用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();

            }

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: