顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2016年2月4日 星期四

C17_12 Timer TimerExample.cs

using System;
using System.Threading;
namespace C17_12
{
    public class StatusChecker
    {
        int invokeCount, maxCount;
        public StatusChecker(int count)
        {
            invokeCount = 0;
            maxCount = count;
        }
        //被定時叫用的方法
        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString());
            if (invokeCount == maxCount)
            {
                invokeCount = 0;
                //將事件狀態設置為終止狀態,允許一個或多個等待執行緒繼續
                autoEvent.Set();
            }
        }
    }
    public class TimerExample
    {
        public static void Main()
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            StatusChecker statusChecker = new StatusChecker(5);
            //建立代理物件TimerCallback,該代理將被定時叫用
            TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus);
            Console.WriteLine("{0} Creating timer.\n",DateTime.Now.ToString("h:mm:ss.fff"));
            //建立一個計時器
            Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 2000);
            autoEvent.WaitOne(5000, false);
            //更改stateTimer 的啟動時間和方法叫用之間的間隔
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");
            autoEvent.WaitOne(5000, false);
            //釋放stateTimer使用的所有資源
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");


        }
    }
}

2016年1月31日 星期日

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

using System;
using System.Threading;
public class SimplePool
{
    public static int Main(string[] args)
    {
        //當前系統是否支援執行緒集區
        bool flag = false;
        //允許執行緒集區中運行最多10個執行緒
        int MaxCount = 10;
        //新建ManualResetEvent物件並且初始化為無信號狀態
        ManualResetEvent mrevent = new ManualResetEvent(false);
        Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);
        OperThread operThread = new OperThread(MaxCount);
        //建立工作項
        //初始化operThread物件的mrevent 屬性
        operThread.mrevent = mrevent;
        Console.WriteLine("Queue to Thread Pool 0");
        try
        {
            //將工作項裝入執行緒集區
            //這裡要用Win200以上版本才有的API
            //所以可能會出現NotSupportException例外
            ThreadPool.QueueUserWorkItem(new WaitCallback(operThread.Beta), new StateInfo(0));
            flag = true;

        }
        catch (NotSupportedException e)
        {
            Console.WriteLine(e.Message);
            flag = false;
        }
        if (flag)
        {
            for (int iItem = 1; iItem < MaxCount; iItem++)
            {
                //插入序列元素
                Console.WriteLine("Queue to Thread Pool {0}", iItem);
                ThreadPool.QueueUserWorkItem(new WaitCallback(operThread.Beta), new StateInfo(iItem));
            }
            Console.WriteLine("Waiting for Thread Pool to drain");
            //等待事件的完成,即執行緒叫用ManualResetEvent.Set方法
            mrevent.WaitOne(Timeout.Infinite, true);
            //WaitOne方法使叫用它的執行緒等待直到mrevent.Set方法被叫用
            Console.WriteLine("Thread Pool has been drained (Event fired)");
            Console.WriteLine();
            Console.WriteLine("Load acrooss threads");
            foreach (object o in operThread.HashCount.Keys)
                Console.WriteLine("{0} {1}", o, operThread.HashCount[o]);
        }
        Console.ReadLine();
        return 0;
    }
}

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();
        }
    }


}

C17_11 執行緒集區例子 StateInfo.cs

public class StateInfo
{
    public int Cookie;
    public StateInfo(int iCookie)
    {
        Cookie = iCookie;
    }
}

2016年1月28日 星期四

C17_10 AutoResetEvent 類別事件 Test.cs

using System;
using System.Threading;
public class Test
{
    static void Main()
    {
        int taskCount = 4;
        AutoResetEvent[] autoEvents = new AutoResetEvent[taskCount];
        ThreadTask[] tasks = new ThreadTask[taskCount];
        for (int i = 0; i < taskCount; i++)
        {
            autoEvents[i] = new AutoResetEvent(false);
            tasks[i] = new ThreadTask(autoEvents[i]);
            ThreadPool.QueueUserWorkItem(tasks[i].Calculation, new InputData(i+1,i+3));
        }
        for(int i=0;i        {
            int index = WaitHandle.WaitAny(autoEvents);
            if(index == WaitHandle.WaitTimeout)
            {
                Console.WriteLine("TimeOut!!");
            }
            else
            {
                Console.WriteLine("finished task for{0}, result:{1}", index,tasks[index].Result);
            }
        }
    }
}

C17_10 AutoResetEvent類別的事件 ThreadTask.cs

using System;
using System.Threading;
public struct InputData
{
    public int X;
    public int Y;
    public InputData(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}
public class ThreadTask
{
    private AutoResetEvent autoEvent;
    private int result;
    public int Result
    {
        get { return result; }
    }
    public ThreadTask(AutoResetEvent ev)
    {
        this.autoEvent = ev;
    }
    public void Calculation(object obj)
    {
        InputData data = (InputData)obj;
        Console.WriteLine("Thread {0} starts calculation", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(new Random().Next(3000));
        result = data.X + data.Y;
        Console.WriteLine("Thread {0} is ready", Thread.CurrentThread.ManagedThreadId);
        autoEvent.Set();
    }

}

2016年1月26日 星期二

C17_9 生產者與消費者問題 MonitorSample.cs

using System;
using System.Threading;
public class MonitorSample
{
    public static void Main()
    {
        //一個標誌為元,如果是 0表示城市沒有出錯,如果是1表示有錯誤發生
        int result = 0;
        Warehouse warehouse = new Warehouse();
        //下面使用warehouse物件初始畫 Producer 和 Consumer兩個類別,生產和消費資數均6次
        Produce prod = new Produce(warehouse, 6);
        Consumer cons = new Consumer(warehouse,6);
        Thread produce = new Thread(new ThreadStart(prod.Threadrun));
        Thread consumer = new Thread(new ThreadStart(cons.ThreadRun));
        //生產者執行緒和消費者執行緒都已經被建立,但是沒有開始執行
        try
        {
            produce.Start();
            consumer.Start();
            produce.Join();
            consumer.Join();
            Console.ReadLine();
        }
        catch(ThreadStartException e)
        {
            //當執行緒因為所處狀態的原因而不能執行被請求的操作
            Console.WriteLine(e);
            result = 1;
        }
        catch(ThreadInterruptedException e)
        {
            //當執行緒在等待狀態的時候終止
            Console.WriteLine(e);
            result = 1;
        }
        //當Main函數沒有回傳直,但下面這條語法可以向父處理序回傳執行結果
        Environment.ExitCode = result;

    }
}

C17_9 生產者與消費者問題 Produce.cs

using System;
public class Produce
{
    Warehouse warehouse;
    //生產者生產次數,初始畫為1
    int quantity = 1;
    public Produce(Warehouse box, int request)
    {
        warehouse = box;
        quantity = request;
    }
    public void Threadrun()
    {
        for (int i = 1; i <= quantity; i++)
        {
            //生產者向操作物件寫入資訊
            warehouse.SetProduce(i);
        }
    }
}
public class Consumer
{
    Warehouse warehouse;
    int quantity = 1;
    public Consumer(Warehouse box, int request)
    {
        warehouse = box;
        quantity = request;
    }
    public void ThreadRun()
    {
        int valReturned;
        for (int i = 1; i <= quantity; i++)
        {
            //消費者從操作物件中讀取資訊
            valReturned = warehouse.GetProduce();
        }
    }
}

C17_9 生產者與消費者問題 Warehouse.cs

using System;
using System.Threading;
public class Warehouse
{
    // 緩衝區,即昌庫
    int whContents;
    //狀態標誌,為true時可以取,為false正在放入
    bool getFlag = false;
    //獲取緩衝區的產品,及消費者
    public int GetProduce()
    {
        lock (this)
        {
            //如果現在不可取
            if (!getFlag)
            {
                try
                {
                    //等待GetProduce方法中叫用Monitor.Pulse方法
                    Monitor.Wait(this);
                }
                catch (SynchronizationLockException e)
                {
                    Console.WriteLine(e);
                }
                catch (ThreadInterruptedException e)
                {
                    Console.WriteLine(e);
                }
            }
            Console.WriteLine("消費產品:{0}", whContents);
            //重置getFlag 標誌,表示消費行為已經完成
            getFlag = false;
            //通知 GetProduce方法(該方法在另外一個執行緒中執行,等待中)
            Monitor.Pulse(this);
        }
        return whContents;
    }
    //向緩衝區放入產品,即生產者
    public void SetProduce(int n)
    {
        lock (this)
        {
            if (getFlag)
            {
                try
                {
                    Monitor.Wait(this);
                }
                catch (SynchronizationLockException e)
                {
                    //當同步方法(指Monitor 累除了enter之外的方法)在非同步的程式碼區被叫用
                    Console.WriteLine(e);
                }
                catch (ThreadInterruptedException e)
                {
                    //當執行蓄在等待狀態的時候終止
                    Console.WriteLine(e);
                }
            }
            //放入產品
            whContents = n;
            Console.WriteLine("生產產品:{0}", whContents);
            getFlag = true;
            //通知另外一個執行緒正在等待的SetProduce方法
            Monitor.Pulse(this);
        }
    }
}

2016年1月25日 星期一

C17_8 lock 語法的使用

using System;
using System.Threading;
using System.Diagnostics;
namespace C17_8
{
    public class Add
    {
        int sum;
        public Add(int initial)
        {
            sum = initial;
        }
        public void DoAdd(int amout)
        {
            lock (this)
            {
                Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name);
                Console.WriteLine(sum);
                Thread.Sleep(5);
                sum = sum + amout;
            }
        }
    }

    public class DoTask
    {
        Add a = new Add(2);
        public void DoWork()
        {
            for (int i = 0; i < 4; i++)
            {
                a.DoAdd(2);
            }
        }
    }
    public class Test
    {
        static Thread[] threads = new Thread[10];
        static void Main()
        {
            DoTask dTask = new DoTask();
            for(int i=0;i<10 i="" p="">            {
                Thread t = new Thread(new ThreadStart(dTask.DoWork));
                threads[i] = t;
            }
            for(int i=0;i<10 i="" p="">            {
                threads[i].Name = i.ToString();
            }
            for(int i=0;i<10 i="" p="">            {
                threads[i].Start();
            }
        }
    }
}

C17_7 執行緒沒有同步的情況

using System;
using System.Threading;
namespace C17_7
{
    public class MyThread
    {
        //定義一個資料欄位
        public int m_x = 0;
        //定義一個寫資料的方法
        public void WriteThread() {
            Thread.Sleep(1000);
            m_x = 5;

        }
        //定義一個讀數據的方法
        public void ReadThread10() {
            int a = 10;
            for (int y = 0; y < 3; y++)
            {
                string s = "ReadThread10:";
                s += Convert.ToString(a) + "#";
                s += a * m_x;
                Console.WriteLine(s);
                Thread.Sleep(1000);

            }
        }
        //定義一個讀數據的方法
        public void ReadThread20() {
            int a = 20;
            for (int y = 0; y < 3; y++)
            {
                string s = "ReadThread20:";
                s += Convert.ToString(a) + "#";
                s += a * m_x;
                Console.WriteLine(s);
                Thread.Sleep(1000);
            }
        }

       
    }
    public class Test
    {
        static void Main()
        {
            //分別建立3個執行緒來運行上面的3個方法,並使用沒有同步的機制的方法來控制執行的運行
            MyThread myThread = new MyThread();
            new Thread(new ThreadStart(myThread.WriteThread)).Start();
            new Thread(new ThreadStart(myThread.ReadThread10)).Start();
            new Thread(new ThreadStart(myThread.ReadThread20)).Start();

        }
    }
}

2015年12月4日 星期五

C17_5 使用Abort方法中止執行緒例子

using System;
using System.Threading;
using System.Security;
namespace C17_5
{
    public class MyThread
    {
        public void TestThread()
        {
            for (int i = 0; i < 3; i++)
            {
                Thread t = Thread.CurrentThread;
                Console.WriteLine(t.Name+"="+i);
                try
                {
                    Thread.Sleep(1);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                }
                catch (ThreadInterruptedException e)
                {
                    Console.WriteLine(e.Message);
                }
                catch (SecurityException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
    public class Test
    {
        public static void Main()
        {
            Console.WriteLine("開始啟動執行緒...");
            MyThread myThread = new MyThread();
            Thread t1 = new Thread(new ThreadStart(myThread.TestThread));
            Thread t2 = new Thread(new ThreadStart(myThread.TestThread));
            t1.Name ="執行緒A";
            t2.Name ="執行緒B";
            Console.WriteLine("執行緒A啟動");
            t1.Start();
             Console.WriteLine("執行緒A終止");
            t1.Abort();
             Console.WriteLine("執行緒B啟動");
            t2.Start();
             Console.WriteLine("執行緒B終止");
            t2.Abort();

        }
       

    }
}

C17_4 執行緒的平行作業例子

using System;
using System.Threading;
namespace C17_4
{
    public class Test
    {
       
     
        public static void ThreadA()
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("執行緒:{0}",i);
                Thread.Sleep(50);
            }
        }
        public static void Main()
        {
            Console.WriteLine("開始啟動執行緒:");
            Thread a = new Thread(new ThreadStart(ThreadA));
            Thread b = new Thread(new ThreadStart(ThreadA));
            a.Start();
            b.Start();
        }
    }

}

C17_3 ThreadStart 使用簡單例子

using System;
using System.Threading;
namespace C17_3
{
    public class MyThread
    {
        string n;
        public MyThread(string n)
        {
            this.n = n;
        }
        public void TestThread()
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("執行緒{0}:{1}", n,i);
            }
        }
    }
    public class Test
    {
        public static void Main()
        {
            Console.WriteLine("開始啟動執行緒:");
            MyThread myThread1 = new MyThread("a");
            MyThread myThread2 = new MyThread("b");
            ThreadStart ts1 = new ThreadStart(myThread1.TestThread);
            ThreadStart ts2 = new ThreadStart(myThread2.TestThread);
            Thread a = new Thread(ts1);
            Thread b = new Thread(ts2);
            a.Start();
            b.Start();
        }
     


    }
}

C17_2 Thread類別的簡單例子

using System;
using System.Threading;
namespace C17_2
{
    public class Test
    {
        public static void ThreadA()
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("執行緒A:{0}",i);
            }
        }
        public static void ThreadB() {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("執行緒B:{0}",i);
            }
        }
        public static void Main()
        {
            Console.WriteLine("開始啟動執行緒");
            Thread a = new Thread(new ThreadStart(ThreadA));
            Thread b = new Thread(new ThreadStart(ThreadB));
            a.Start();
            b.Start();
        }
    }
}

2015年11月29日 星期日

GetProcesses

using System;
using System.IO;
using System.Diagnostics;
public class Program
{
    public static void Main()
    {
        Process[] processOnComputer = Process.GetProcesses();
     
        foreach (Process p in processOnComputer)
        {
            Console.WriteLine(p.ToString());
        }
        Console.WriteLine(processOnComputer.Length);
    }
}

Kill

using System;
using System.IO;
using System.Diagnostics;
public class Program
{
    public static void Main()
    {
        Process[] p = Process.GetProcessesByName("notepad");
        if (p.Length > 0)
        {
            if (!p[0].HasExited)
            {
                if (p[0].Responding)
                {
                    p[0].CloseMainWindow();
                }
                else
                {
                    p[0].Kill();
                }
            }

        }
    }
}

Process()

using System;
using System.IO;
using System.Diagnostics;
public class Program
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "notepad.exe";
        p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
        p.Start();

    }
}

C17_1 執行命令,並關閉處理

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections;
namespace C17_1
{
    public class Program
    {
        ///
        ///運行cmd命令
        ///
        ///命令
        ///
        public static string Cmd(string[] cmd)
        {
            foreach(string a in cmd)
            {
                Console.WriteLine(a);
            }
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            for (int i = 0; i < cmd.Length; i++)
            {
                p.StandardInput.WriteLine(cmd[i].ToString());
            }
            p.StandardInput.WriteLine("exit");
            string result = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            return result;
        }
        ///
        ///關閉處理序
        ///
        ///處理序名稱
        ///
        public static bool CloseProcess(string ProcName)
        {
            bool result = false;
            ArrayList pList = new ArrayList();
            string tempName = "";
            int begpos;
            int endpos;
            foreach(Process p in Process.GetProcesses())
            {
                tempName = p.ToString();
                begpos = tempName.IndexOf("(")+1;
                endpos = tempName.IndexOf(")");
                tempName = tempName.Substring(begpos,endpos-begpos);
                pList.Add(tempName);
                if (tempName == ProcName)
                {
                    if (!p.CloseMainWindow())
                    {
                        //當發送關閉視窗命令無效時強行結束處理序
                        p.Kill();
                    }
                    result = true;
                }
            }
            return result;
        }
        public static void Main()
        {
            string[] cmd = new string[] {"ping 192.168.1.1","ipconfig" };
            MessageBox.Show(Cmd(cmd));
            CloseProcess("cmd.exe");
        }
    }
}

2015年11月27日 星期五

C16_5 使用特性自行定義序列化

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace C16_5
{
    ///
    ///自行訂議序列化類別
    ///
    [Serializable]
    public class TestAttributeSerializable
    {
        public string a = "HelloWorld";
        //序列化時叫用
        [OnSerializing]
        internal void OnSerializing(StreamingContext context)
        {
            a = a.ToLower();
        }
        //反序列化時叫用
        [OnDeserialized]
        internal void OnDeserialized(StreamingContext contest)
        {
            a = a.ToUpper();
        }
    }
    public class Test
    {
        ///
        ///BinaryFormatter 進行序列化
        ///
        public void DoSerialize()
        {
            TestAttributeSerializable test = new TestAttributeSerializable();
            Stream stem = File.Open("c:\\TestAttributeSerializable.dat", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stem,test);
            stem.Close();
            Console.WriteLine(test.a);
        }
        ///
        ///BinaryFormatter 進行反序列化
        ///
        public void DoDeserialize()
        {
            Stream steam = File.Open("c:\\TestAttributeSerializable.dat",FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            TestAttributeSerializable test = (TestAttributeSerializable)bf.Deserialize(steam);

            steam.Close();
            Console.WriteLine(test.a);
        }
        public static void Main()
        {
            TestAttributeSerializable test = new TestAttributeSerializable();
            Console.WriteLine("原始資料{0}",test.a);
            Test test1 = new Test();
            Console.WriteLine("序列化後數據:");
            test1.DoSerialize();
            Console.WriteLine("反序列化數據:");
            test1.DoDeserialize();
        }

    }
}