程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 線程池讀取List<T>實例,線程list

線程池讀取List<T>實例,線程list

編輯:C#入門知識

線程池讀取List<T>實例,線程list


private static readonly Object ThisLock = new object();
private static readonly AutoResetEvent AutoReset = new AutoResetEvent(false);
private static int _selectindex;
private const int Threadcount = 10;
private int _finishcount;
List<T> _datamodellist;

public void LoadPage()
{
    Grid();
}

private void Grid()
{
   _list.Clear(); _finishcount = 0; _selectindex = 0; _datamodellist = GetAll(); for (var i = 0; i < Threadcount; i++) { var thread = new Thread(DoTask); thread.Start(1); } AutoReset.WaitOne();//等待線程池完成 //do something } public void DoTask(Object index) { while (_selectindex < _datamodellist.Count) { lock (ThisLock) //鎖定後只有一個線程進入直至塊內代碼執行完 { if (_selectindex >= _datamodellist.Count) continue; daimamodel = _datamodellist[_selectindex]; _selectindex++; } //do something _finishcount++; if (_finishcount == _datamodellist.Count) { AutoReset.Set();//最後一個線程完成後才終止
     }
  }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved