Skip to main content
 首页 » 编程设计

c#之HttpWebRequest 在另一个线程中返回请求的结果 (Monotouch)

2024年01月01日5252php

这个问题是关于 Monotouch 的,但它可能是一般的 .NET 问题或 Mono 库的问题。

我遇到了很长一段时间以来遇到的最奇怪的问题。

我启动了 2 个线程,每个线程创建一个 HttpWebRequest。这些线程同时启动(好吧,相隔一毫秒)。发生的情况是第一个 HTTP 请求 (url1) 对 GetResponse() 的调用接收到第二个 HTTP 请求 (url2) 的内容。发生这种情况时,第二个 HTTP 请求会在 30 秒后超时。

这不会每次都发生,但确实有 5 次发生了 4 次。

这是代码:(经过简化以生成工作测试用例)

public void Launch() 
{ 
   Thread thread1 = new Thread(() => { GetData("http://url1"); }); 
   Thread thread2 = new Thread(() => { GetData("http://url2"); }); 
 
   thread1.Start(); 
   thread2.Start(); 
} 
 
public static void GetData(string url) 
{ 
   try 
   { 
      XDocument xDoc; 
 
      var webRequest = HttpWebRequest.Create(url); 
 
      using (var response = webRequest.GetResponse()) 
      { 
         using (var stream = response.GetResponseStream()) 
         { 
             xDoc = XDocument.Load(stream); 
 
             Logger.Default.Log("Result for {0}: {1}", url, xDoc); 
         } 
      } 
   } 
   catch(Exception ex) 
   { 
       Logger.Default.Log("Result for {0}: [Exception: {1}]", url, ex.Message); 
   } 
} 

这是输出(5 次中有 4 次):

Result for http://url1: <contents of http://url2> 
Result for http://url2: [Exception: timeout...] 

当一切正常时(5 次中有 1 次):

Result for http://url1: <contents of http://url1> 
Result for http://url2: <contents of http://url2> 

请您参考如下方法:

听起来不像一般的 .net 行为。

听起来像是一个错误 - 向 xamarin 的 bugzilla 报告它? https://bugzilla.xamarin.com/