线程池读取List<T>实例_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 线程池读取List<T>实例

线程池读取List<T>实例

 2015/4/20 12:33:00  hot's  程序员俱乐部  我要评论(0)
  • 摘要:privatestaticreadonlyObjectThisLock=newobject();privatestaticreadonlyAutoResetEventAutoReset=newAutoResetEvent(false);privatestaticint_selectindex;privateconstintThreadcount=10;privateint_finishcount;List<T>_datamodellist;publicvoidLoadPage()
  • 标签: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();//最后一个线程完成后才终止
     }
  }
}

 

发表评论
用户名: 匿名