標籤:adt 效率 private copy ima ++ UI invoke http
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; }
好了。簡單的多執行緒。希望大家可以學習。歡迎大家指導~~
C# 多線程、控制線程數提高迴圈輸出效率