目前在工作中遇到web访问timeout问题,于是我的想法是在执行访问的时候设计一个计数器,等到访问时间过长就抛出一个异常。现在是不想每个函数都单独写个计算的函数,想写个通用的函数,在每个函数中调用,但是这个函数要求和下面的主体程序并行运行,这个函数的功能就是检查主体函数的运行时间。实在没有什么好的办法,希望高手求教伪代码:
 public void BingLocaleStrings_OpenTest()
        {
            try
            {
               //调用TimeOut程序,这里要求和下面的主体程序并行运行,主要是测试主体程序的运行时间的。
               TimeOut();
               //主体程序
            }
            catch (Exception ex)
            {
                //输出错误信息
            }
            finally
            {
                //善后处理
            }
        } public void TimeOut(int Outtime)
{
   int begin = 0;
            while(begin<=Outtime)
            {
                 //计时计算
                 sleep(1000);
                 begin++;
            }
            Exception timeout = new Exception("TimeOut:The run time is too long!");
            throw timeout;
}

解决方案 »

  1.   

    public void BingLocaleStrings_OpenTest()
            {
                try
                {
                   //调用TimeOut程序,这里要求和下面的主体程序并行运行,主要是测试主体程序的运行时间的。
                   Thread newThread=new Thread(TimeOut);
                 newThread.start();
                   //主体程序
                }
      

  2.   

    Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    处理异常
    使用ThreadPool.QueueUserWorkItem方法
    使用BackgroundWorker
    BackgroundWorker 实现原理是基于事件的异步处理模式。