码迷,mamicode.com
首页 > 其他好文 > 详细

信号量(Semaphore)

时间:2015-08-05 20:13:51      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private Semaphore semaphore;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //创建信号量
            semaphore = new Semaphore(Convert.ToInt32(numericUpDown1.Value), Convert.ToInt32(numericUpDown1.Value),"MySemaphore");
            
            for (int i = 0; i < 100;i++ )
            {
                 //实体类用于传i
                TaskObject task = new TaskObject(i);
                Thread th = new Thread(new ThreadStart(delegate
                {
                    
                    work2(task);
                }));
                th.IsBackground = true;
                th.Start();                
            }  
         
            //semaphore.Close();
        }

        private void work2(TaskObject task)
        {
            semaphore.WaitOne();
            this.Invoke(new MethodInvoker(delegate
            {
                textBox1.AppendText(task.ID.ToString()+ "\r\n");              
            }));
            Thread.Sleep(1000);
            semaphore.Release(1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }
    }
}

 

信号量(Semaphore)

标签:

原文地址:http://www.cnblogs.com/milest/p/4705458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!