首页 > 学院 > 开发设计 > 正文

线程池读取List<T>实例

2019-11-17 02:26:19
字体:
来源:转载
供稿:网友

线程池读取List<T>实例

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表