生产者消费者

基于 生产者消费者模式

1.生产者生产出产品

2.消费者不听的消费产品

详细代码

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

namespace 生产者消费者
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private List<string> data = new List<string>();

        private void Form1_Load(object sender, EventArgs e)
        {
            //新建线程   开启任务
            Thread threadXFZ = new Thread(XFZ);
            threadXFZ.IsBackground = true;
            threadXFZ.Start();

            //TextBox.CheckForIllegalCrossThreadCalls = false;
        }

        //充当消费者角色  不停的消费
        private void XFZ()
        {
            while (true)
            {
                //查看商品列表,有商品就消费
                foreach (string s in data.ToArray())
                {
                    MyDelegate d = (txt) => {
                        txtLog.AppendText(txt + "\n");
                    };
                    txtLog.Invoke(d,s);
                    data.Remove(s);//消费了商品就把商品从“仓库”中移除掉
                }

                //睡5秒钟
                Thread.Sleep(10*1000);
                //降低CPU占用率,不是生产出商品来立即消费,而是累积5秒钟
            }
        }

        //充当生产者角色  生产data产品
        private void button1_Click(object sender, EventArgs e)
        {
            data.Add(txtSCZ.Text);
            txtSCZ.Clear();
            txtSCZ.Focus();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //在用for对集合遍历过程中,对集合修改可能会造成数据混论
            //在用foreach对集合遍历过程中,对集合修改是不允许的
            //foreach (string s in data)
            //{
            //    MessageBox.Show(s);
            //    data.Remove(s);
            //}

            //也可以倒序删除
            //ToArray以后生成的数组就和原List无关
            foreach (string s in data.ToArray())
            {
                MessageBox.Show(s);
                data.Remove(s);//消费了商品就把商品从“仓库”中移除掉
            }
        }
    }
    delegate void MyDelegate(string s);
}

 

 

posted @ 2013-06-04 12:49  张国朋  阅读(165)  评论(0编辑  收藏  举报