0

子线程正在等待来自网络服务器的响应,并且也具有超时值。
如果超时值在从 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;
  }
}


谢谢。

4

1 回答 1

1

据我了解,如果您的子线程超时,您会问如何登录到文件?

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

例子:

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

作为GetResponse()抽象,WebException它实际上是由 的FileWebRequestHttpWebRequest实现抛出的GetResponse()

于 2013-04-03T11:02:33.130 回答