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類是會直接得到兩種不同結果的,一個是線程安全的一個是線程不安全的。(不用謝請叫我雷鋒)