六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 74|回复: 0

c#线程基础之原子操作

[复制链接]

升级  85%

884

主题

884

主题

884

主题

探花

Rank: 6Rank: 6

积分
2700
 楼主| 发表于 2013-2-1 11:38:39 | 显示全部楼层 |阅读模式
使用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();            }        }    }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表