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();//最後一個線程完成後才終止
}
}
}