您的位置:首页 > 移动开发 > Objective-C

C# 多线程Synchronization和ContextBoundObject应用

2016-03-10 20:27 429 查看
C#处理多线程可以说是方式多种多样,多到你都不知道选择那个好,直到Task的出现,Task类的灵活机制和极为优美的写法让所有.net开发者眼前一亮,但是今天我们要说一说一个冷门的多线程安全处理机制,Synchronization属性和ContextBoundObject类,这两个一起使用可以让一个类的实例处于上下文的线程安全中,注意不需要写一大堆lock,只需要在类上有Synchronization这个属性和继承ContextBoundObject,没错就是这么简单这么优雅,让我们一起欣赏一下我的简易Demo源码。

(我们不深入讨论上下文机制既然用C#让我们先知其然而不知所以然吧这或许是C#语言的初衷)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{

class Program
{
[Synchronization(true)]
class Test : ContextBoundObject
{
public  int count = 0;

public void Display()
{
count++;
Console.WriteLine("ContextID:{1},统计:{0}", count, Thread.CurrentContext.ContextID);
}
}

static void Main(string[] args)
{
Test test = new Test();
Thread thread1 = new Thread(new ThreadStart(() =>
{
for (int i = 0; i < 50; i++)
{
test.Display();
}
}));

Thread thread2 = new Thread(new ThreadStart(() =>
{
for (int i = 0; i < 50; i++)
{
test.Display();
}
}));

thread1.Start();
thread2.Start();
while (true)
{

}
}
}
}


大家试试这段代码就知道,加不加Synchronization属性和ContextBoundObject类是会直接得到两种不同结果的,一个是线程安全的一个是线程不安全的。(不用谢请叫我雷锋

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