c#線程基礎之線程式控制制

來源:互聯網
上載者:User

用ManualResetEvent和AutoResetEvent可以很好的控制線程的運行和線程之間的通訊。msdn的參考為: http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.aspx http://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx 下面我寫個例子,這裡類比了一個線程更新資料,兩個線程讀取資料。更新的時候需要阻止讀取的兩個現成工作。而另外還有一個訊號量來控制線程的退出。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace WindowsApplication35{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        System.Threading.ManualResetEvent mEvent = new System.Threading.ManualResetEvent(true);        //判斷安全執行緒退出的訊號量        System.Threading.ManualResetEvent mEventStopAll = new System.Threading.ManualResetEvent(false);        //*******ManualResetEvent的用法。        private void button1_Click(object sender, EventArgs e)        {            //一個線程類比寫入            new System.Threading.Thread(invokeWrite).Start();            //兩個線程類比讀取            new System.Threading.Thread(invokeRead).Start();            new System.Threading.Thread(invokeRead).Start();        }        private void invokeWrite()        {            for (int i = 0; i < 100; i++)            {                //判斷安全執行緒退出                if (mEventStopAll.WaitOne(10, false) == true) break;                //設定訊號量,假設更新資料需要2秒,每更新一次暫停2秒.                mEvent.Reset();                Console.WriteLine("正在更新...");                System.Threading.Thread.Sleep(2000);                mEvent.Set();                System.Threading.Thread.Sleep(2000);            }        }        private void invokeRead()        {            while (mEvent.WaitOne() == true)            {                //判斷安全執行緒退出                if (mEventStopAll.WaitOne(10, false) == true) break;                //假設讀取一體資料用10毫秒.他需要判斷訊號量開關.                Console.WriteLine("讀取一條資料:");                System.Threading.Thread.Sleep(10);            }        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            mEventStopAll.Set();        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.