处理线程中的线程中止异常....?

时间:2013-04-03 09:22:10

标签: c# asp.net multithreading thread-safety

子线程正在等待来自Web服务器的响应,并且也具有超时值。
如果在从Web服务器获得响应之前首先出现超时值,它将继续请求超时和线程中止异常。
我们如何处理这个并登录到文本文件......?
父线程

  public void  Save()
 {
  List<Job> Jobs = PickJobs();

  int workerThreads = 0,compThreads = 0;
  ThreadPool.GetMinThreads(workerThreads, compThreads);

  int requiredThreads = 15;
  ThreadPool.SetMaxThreads(requiredThreads, compThreads);

  WaitCallback waitCallBack = default(WaitCallback);
  ManualResetEvent mEvent = default(ManualResetEvent);

 foreach (Job _job in Jobs) 
   {
   waitCallBack = new WaitCallback(CallBackFunc);
   mEvent = new ManualResetEvent(false);
   events.Add(mEvent);
   ThreadPool.QueueUserWorkItem(waitCallBack, new UrlData(_job, mEvent, HttpContext.Current));
   }
     WaitHandle.WaitAll(events.ToArray(), 300000);//05 Minutes
 }

子线程

private void CallBackFunc(object obj)
{
     UrlData msgObj = (UrlData)obj;
   WebRequest lWebRequest = WebRequest.Create(psUrl);
   lWebRequest.Timeout = 60000;
   WebResponse lWebResponse = lWebRequest.GetResponse;

    msgObj.FinishEvent.Set();
}

跨线程通信的对象

public class UrlData
{
public Job job;
public ManualResetEvent FinishEvent;
public HttpContext HttpContextRef;

public UrlData(Job pJob, ManualResetEvent pEvent, HttpContext pContext)
  {
      job= pJob;
      FinishEvent = pEvent;
      HttpContextRef = pContext;
  }
}


谢谢。

1 个答案:

答案 0 :(得分:1)

根据我的理解,如果你的子线程超时,你会问如何登录文件?

如果是这样,我相信如果在收到响应之前达到超时限制,则GetResponse()方法会抛出WebException。因此,围绕使用try-catch语句进行GetResponse()调用的行应允许您将信息记录到文件中。

示例:

try {
    WebResponse lWebResponse = lWebRequest.GetResponse;
} catch (WebException ex) {
    // Write to file code in here
}

由于GetResponse()是抽象的,WebException实际上是由GetResponse()的{​​{3}}或FileWebRequest实现引发的。