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


 

C#多線程及控制線程數量,對for循環輸出效率。

 

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

思路:

如果要刪除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;
        }

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM