线程池读取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();//最后一个线程完成后才终止
     }
  }
}

 

你可能感兴趣的:(list)