天天看點

C# 多線程、控制線程數提高循環輸出效率

原文: C# 多線程、控制線程數提高循環輸出效率 C#多線程及控制線程數量,對for循環輸出效率。

C# 多線程、控制線程數提高循環輸出效率

雖然輸出不規律,但是效率明顯提高。

思路:

如果要删除1000條資料,隻使用for循環,則一個接着一個輸出。是以,把1000條資料分成seed段,每段10條資料。

int seed = Convert.ToInt32(createCount.Value) % 10 == 0 ? Convert.ToInt32(createCount.Value) / 10 : Convert.ToInt32(createCount.Value) / 10 + 1;      

注:createCount.Value的值是具體輸出資料的數量

這裡把資料配置設定給seed個線程去處理,每個線程隻輸出10個資料。

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做簡單處理。例如 我要輸出

000000

000001

000002

000003

........

從上面的代碼可以看出,我是使用for來遞增的。是以是整型,前面的0随着數值的大小不斷改變個數。

//處理數字前面有多少個0
        private string GetZero(int leng)
        {
            string result = "";
            for (int i = 0; i < leng; i++)
            {
                result += "0";
            }
            return result;
        }      

好了。簡單的多線程處理。希望大家可以學習。歡迎大家指導~~