首页 > 代码库 > 多线程
多线程
信号量控制线程池
//信号量 Semaphore semahoro; private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(ThreadPooltemp)); t.Start(); } private void ThreadPooltemp() { semahoro = new Semaphore(3, 3); var ehs = new List<ManualResetEvent>(); for (int i = 0; i < 10; i++) { var m = new ManualResetEvent(false); ehs.Add(m); ThreadHelper th = new ThreadHelper(); th.id = i; ThreadPool.QueueUserWorkItem(h => { semtemp(th); m.Set(); }); } //第一种方式等待 WaitHandle.WaitAll(ehs.ToArray()); //第二种方式等待 foreach (var m in ehs) { m.WaitOne(); } MessageBox.Show("ThreadPool >>> ok!"); } public void semtemp(ThreadHelper thh) { semahoro.WaitOne(); Run(thh); semahoro.Release(1); } private void Run(ThreadHelper mny) { this.Invoke(new EventHandler(delegate { textBox1.AppendText(mny.id.ToString() + "\r\n"); })); Thread.Sleep(2000); //第二种委托 //this.Invoke(new MethodInvoker(delegate //{ // dataGridView1.Rows[row].Cells[cll].Value = http://www.mamicode.com/con;>//})); }
信号量构建多线程
//信号量 Semaphore semahoro; private void button2_Click(object sender, EventArgs e) { Thread th = new Thread(new ThreadStart(delegate { sem(); })); th.IsBackground = true; th.Start(); } public void sem() { semahoro = new Semaphore(3, 3); var ehs = new List<ManualResetEvent>(); for (int i = 0; i < 10; i++) { var m = new ManualResetEvent(false); ehs.Add(m); ThreadHelper thh = new ThreadHelper(); thh.id = i; Thread th = new Thread(new ThreadStart(delegate { semtemp(thh); m.Set(); })); th.IsBackground = true; th.Start(); } //第一种方式等待 WaitHandle.WaitAll(ehs.ToArray()); //第二种方式等待 foreach (var m in ehs) { m.WaitOne(); } this.Invoke(new MethodInvoker(delegate { MessageBox.Show(this, "Semaphore >>> ok!"); })); } public void semtemp(ThreadHelper thh) { semahoro.WaitOne(); Run(thh); semahoro.Release(1); } private void Run(ThreadHelper mny) { this.Invoke(new EventHandler(delegate { textBox1.AppendText(mny.id.ToString() + "\r\n"); })); Thread.Sleep(2000); //第二种委托 //this.Invoke(new MethodInvoker(delegate //{ // dataGridView1.Rows[row].Cells[cll].Value = http://www.mamicode.com/con;>//})); }
也可以把线程全部加到List集合
//投递完毕,等待线程完成!
for (int i = 0; i < ths.Count; i++)
{
while (ths[i].ThreadState != System.Threading.ThreadState.Stopped)
{
Application.DoEvents();
}
}
多线程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。