C# 线程资源同步方式总结

Posted by & filed under C#.

在现代的程序开发中,资源的同步是一个比较重要的课题,在.Net中,对这部分有很丰富类库供我们使用,现在总结一下在各种情况下对资源同步的
机制。

1.将字段声明为volatile

当一个字段被声明为volatile时,CLR中一些管理代码和内存的内部机制将负责对字段进行同步,并且总能保证读取到的字段信息都为最新的值,被声明为
volatile的字段必须具备以下特征之一

1.为引用类型
2.一个指针(在不安全代码中)
3.sbyte,byte,short,ushort,int,uint,char,float,bool
4.一个使用底层类型的枚举类型

2.使用System.Threading.Interlocked 类

在许多增对整数的操作中,我们都比较容易忽视线程的问题,例如执行下列代码

i = i + 1;

实际上,上述代码分为3步骤
1).  从内存中,读取i的值
2).  将读取出来的值加1
3).  将新的值写入内存中

在单线程上,这个操作不会有任何问题,但是当i被多个线程访问时,问题就出现了,对i进行修改的线程,在上述的任何一部都有可能被其它读取线程打断,想象一下,
当操作线程执行完第二步,准备将新的值写入内存中时,此时其它读取线程获得了执行权,这时读取到的i的值并不是我们想要的,因此,这个操作不具备原子性,在.Net中,使用Interlocked类能确保操作的原子性,Interlocked类有以下的方法

Increment
Decrement
Exchange

上述的方法的参数都为带ref 标识的参数,因此我们说,这些方法保证了数据的原子性,在多线程中,涉及到整数的操作时,数据的原子性值得考虑,Interlocked的操作代码如下

            int i = 0;
            System.Threading.Interlocked.Increment(ref i);
            Console.WriteLine(i);
            System.Threading.Interlocked.Decrement(ref i);

Visual C# IDE Refactoring Tools

Posted by & filed under C#.

The C# IDE includes a suite of tools that automate many common code refactoring tasks. Refactoring is a formal and mechanical process, used to modify existing code in such a way that it is improved while preserving the program’s intended …

Jump To C#

Posted by & filed under C#.

リンク: Jump To C#.

When I started learning C# half the time I was trying to find Java equivalents so that I can learn effectively,

leveraging my existing Java skills.  At times I was so frustrated by my knowledge …