2016年1月31日 星期日

C17_11 執行緒集區的例子 OperThread.cs

using  System;
using System.Collections;
using System.Threading;
public class OperThread
{
    public Hashtable HashCount;
    public ManualResetEvent mrevent;
    public static int iCount = 0;
    public static int iMaxCount = 0;
    public OperThread(int MaxCount)
    {
        HashCount = new Hashtable(MaxCount);
        iMaxCount = MaxCount;
    }
    //執行緒集區裡的執行緒將叫用Beta方法
    public void Beta(Object state)
    {
        //輸出當前執行緒的Hash編碼值和Cookie的值
        Console.WriteLine(" {0} {1} : ", Thread.CurrentThread.GetHashCode(), ((StateInfo)state).Cookie);
        Console.WriteLine("HashCount.Count=={0},Thread.CurrentThread.GetHashCode()=={1}", HashCount.Count, Thread.CurrentThread.GetHashCode());
        lock (HashCount)
        {
            //如果當前的Hash表中沒有當前執行的Hash值,則新增
            if(!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
                HashCount.Add(Thread.CurrentThread.GetHashCode(),0);
            HashCount[Thread.CurrentThread.GetHashCode()] = ((int)HashCount[Thread.CurrentThread.GetHashCode()]) + 1;
        }
        Thread.Sleep(2000);
        //Interlocked.Increment() 操作是一個原子操作
        Interlocked.Increment(ref iCount);
        if(iCount == iMaxCount)
        {
            Console.WriteLine();
            Console.WriteLine("Setting mrevent ");
            mrevent.Set();
        }
    }


}

沒有留言: