转 C#多线程及控制线程数量,对for循环输出效率

转自:http://www.cnblogs.com/StupidsCat/archive/2012/12/07/2807503.html

添加控件

NumbericUpDown,重命名为createCount,

textbox重命名为:f_groundcode,

textbox重命名为:f_ticketno

button重命名为:btnCreate

richtextbox重命名为:txtResult

int threadCountTmp = 0;//任务线程分派数
        private void btnCreate_Click(object sender, EventArgs e)
        {
            int seed = Convert.ToInt32(createCount.Value) % 10 == 0 ? Convert.ToInt32(createCount.Value) / 10 : Convert.ToInt32(createCount.Value) / 10 + 1;

            for (int i = 0; i < seed; i++)
            {
                Thread threadTmp = new Thread(new ParameterizedThreadStart(TempOut));
                threadTmp.Start(i);
                threadCountTmp++;
                Application.DoEvents();//响应窗口状态
                while (true) { if (threadCountTmp < 10) break; }//推拉窗式控制多线程 线程数10
            }
        }
        //分段后的数据发布给其它线程
       
        public void TempOut(object o)
        {
            int tmp = Convert.ToInt32(o) * 10;
            int i = tmp;
            for (; i < (tmp + 10 <= createCount.Value ? tmp + 10 : createCount.Value); i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(ResultOut));
                thread.Start(i);
                threadCount++;
                while (true) { if (threadCount < 10) break; }//推拉窗式控制多线程   线程数10
            }
            threadCountTmp--;
        }
        delegate void TextTmp(object o);//声明委托
        int threadCount = 0;//任务线程
        //委托函数
        public void ResultOut(object o)
        {
            if (!txtResult.InvokeRequired)
            {
                txtResult.Text = "\n" + f_groundcode.Text + "," + f_ticketno.Text + DateTime.Now.ToLongDateString().Replace("-", "") + GetZero(6 - o.ToString().Length) + o.ToString() + "," + DateTime.Now.ToLongDateString().Replace("-", "") + DateTime.Now.ToLongTimeString().Replace(":", "") + txtResult.Text;
            }
            else
            {
                TextTmp tmpDel = new TextTmp(ResultOut);
                this.Invoke(tmpDel, o);
            }
            threadCount--;
        }
        //处理数字前面有多少个0
        private string GetZero(int leng)
        {
            string result = "";
            for (int i = 0; i < leng; i++)
            {
                result += "0";
            }
            return result;
        }

运行效果图:

 

原文地址:https://www.cnblogs.com/bantongshui/p/3170008.html