[c#] SmartThreadPool[2]

转自:http://www.xiaocan.me/archives/568

处理线程执行过程中出现的错误

private void button3_Click ( object sender, EventArgs es )
{
    //处理线程执行过程中出现的错误
    SmartThreadPool stp = new SmartThreadPool ( ) ; //如果需要将线程池设置为调用start的时候才运行,需要设置其StartSuspended参数为true,然后为其调用start方法来启动
    IWorkItemResult < double > ret = stp . QueueWorkItem ( new Amib . Threading . Func < double, double, double > (Diverse ), 10.0, 0 ) ;
    //接收错误的句柄
    stp . Start ( ) ;
    Exception e = null ;
    double resule = ret . GetResult ( out e ) ; //在取出结果的时候判断是否有错误产生
    if (e != null )
    {
        //在这里进行错误处理,错误在InnerException中
        MessageBox . Show (e . InnerException . Message ) ;
    }
    else
    {
        MessageBox . Show (resule . ToString ( ) ) ;
    }
    stp . Shutdown ( ) ;
}

private double Diverse ( double x, double y )
{
    return x /y ;
}

使用线程分组

private void button4_Click ( object sender, EventArgs e )
{
    //这里演示了线程的分组
    SmartThreadPool stp = new SmartThreadPool ( ) ;
    //创建一个分组并用这个分组管理
    IWorkItemsGroup mainGroup = stp . CreateWorkItemsGroup ( 1 ) ; //如果需要设置这个分组为调用start的时候才开始运行,需要传入WIGStartInfo参数,将其参数中的StartSuspended设置为true然后调用分组的start方法
    //向分组中添加任务->当然可以有返回值
    mainGroup . QueueWorkItem ( new WorkItemCallback (GetObjectString ), 123 ) ;
    //分组等待所有任务完成
    mainGroup . WaitForIdle ( ) ;
    //关闭
    stp . Shutdown ( ) ;
}

以下是SmartThreadPool的部分解释

SmartThreadPool smartThreadPool = new SmartThreadPool ( ) ;

//获取当前线程池中的工作线程数,与InUseThreads可能会有差别,因为InUseThreads不包含Idle状态的线程
int threadNum = smartThreadPool . ActiveThreads ;
//取消所有工作项,如果工作项在执行,那么等待工作项执行完
smartThreadPool . Cancel ( ) ;
//如果不想等待工作项执行完,
smartThreadPool . Cancel ( true ) ;
//线程池的最大并发数,即MaxWorkerThreads,
//如果修改后的Concurrency小于MinWorkerThreads,那么MinWorkerThreads也会随之改变
smartThreadPool . Concurrency = 25 ;
//创建一个工作组,最大并发为3,工作组在后面会详细说明,
smartThreadPool . CreateWorkItemsGroup ( 3 ) ;
//卸载线程池
smartThreadPool . Dispose ( ) ;
//反回所有未执行的工作项的参数对象
smartThreadPool . GetStates ( ) ;
//获取线程池中正在工作的线程数,与ActiveThreads会有差别,因为ActiveThreads可能包含Idle状态的线程
int useThreadNum = smartThreadPool . InUseThreads ;
//当线程池用没有工作项时,反回true,否则,反回false
bool IsIdle = smartThreadPool . IsIdle ;
//同时并行执行多个方法,并且阻塞到所有工作项都执行完,这里会有多少个工作项就会创造多少个线程,
smartThreadPool . Join ( new Action [ ] { new Action (Test ) } ) ;
//获取或设置最大线程数,即MaxWorkerThreads,
smartThreadPool . MaxThreads = 25 ;
//最小线程数,当没有工作项时,线程池最多剩余的线程数
smartThreadPool . MinThreads = 0 ;
//线程池的名称,没什么特殊的用处,
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值