首页 > 代码库 > C#多线程并发精确控制例子

C#多线程并发精确控制例子

技术分享

网上找了很久都找不到好点的例子,于是自己写了一个!

主要演示多线程,委托,回调 
核心代码:

 

public partial class frmStart : Form    {        #pragma warning disable 0618        public delegate  void AddCulumCallBack(int index,int i);        public AddCulumCallBack addCulumCallBack;        ManualResetEvent resumeEvent = new ManualResetEvent(false);         public frmStart()        {            InitializeComponent();            addCulumCallBack = new AddCulumCallBack(AddCulum);        }        public void AddCulum(int index,int i)        {            this.lvShow.Items[index].SubItems[1].Text = "多线程并发运行测试:"+i.ToString();        }        private void btnInitil_Click(object sender, EventArgs e)        {                        for (int i = 0; i < 30; i++)            {                ListViewItem lvi = new ListViewItem("");                lvi.SubItems.Add(i.ToString());                this.lvShow.Items.Add(lvi);            }        }        private string GetWebRequest(string url)        {            Uri uri = new Uri(url);            WebRequest myReq = WebRequest.Create(uri);            WebResponse result = myReq.GetResponse();            Stream receviceStream = result.GetResponseStream();            StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));            string strHTML = readerOfStream.ReadToEnd();            readerOfStream.Close();            receviceStream.Close();            result.Close();            return strHTML;        }        private void btnStart_Load(object sender, EventArgs e)        {        }        List<Thread> listThread;        private void button1_Click(object sender, EventArgs e)        {            listThread = new List<Thread>();            for (int i = 0; i < 30; i++)            {                object index = i;                Thread myThread = new Thread(Method);                myThread.Start(i);                listThread.Add(myThread);            }                    }        public void Method(object index)         {            string a = GetWebRequest("http://www.baidu.com");            for (int i = 0; i < 10000; i++)            {                this.BeginInvoke(addCulumCallBack, index,i);                Thread.Sleep(100);            }                    }        private void btnPauseThread_Click(object sender, EventArgs e)        {            foreach (Thread item in listThread)            {                item.Suspend();            }        }        private void btnGoAhead_Click(object sender, EventArgs e)        {            foreach (Thread item in listThread)            {                item.Resume();                            }        }        private void btnClose_Click(object sender, EventArgs e)        {            foreach (Thread item in listThread)            {                item.Abort();                            }            listThread.Clear();                    }    } 

  

 

C#多线程并发精确控制例子