2015-01-09 81 views
1

我有一个奇怪的问题。我在Visual Studio 2013中创建了一个应用程序,该应用程序在Windows中正常工作。然后我将它移植到Mono,因为我需要应用程序在Linux控制台中运行。HttpWebRequest导致应用程序挂起

该应用程序在Mono中工作正常,但现在它停止在Windows中工作。源代码是相同的。它实际上是Mono源代码的复制和粘贴。当我在Windows中运行应用程序时,它只是出现黑色控制台窗口并“挂起”。这里是挂起的代码:

static void Main(string[] args) 
{ 
    string orders = GetLoginHtml(); 

    Console.WriteLine(orders); 
} 

private static string GetLoginHtml() 
{ 
    var request = (HttpWebRequest)WebRequest.Create(LoginUrl); 
    var cookieJar = new CookieContainer(); 

    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.CookieContainer = cookieJar; 
    using (var requestStream = request.GetRequestStream()) 
    { 
     string content = "Email=" + Username + "&Passwd=" + Password; 
     requestStream.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetBytes(content).Length); 

     // The next line is where it hangs 

     using (var sr = new StreamReader(request.GetResponse().GetResponseStream())) 
     { 
      string html = sr.ReadToEnd(); 
      string galxValue = ParseOutValue(html, "GALX"); 

      return GetLoginHtml2(galxValue, cookieJar); 
     } 
    } 
} 

我评论了线条悬挂在哪里。我为什么,至少在不给我一个错误的时间方面感到不知所措。我跑了小提琴手,我发现它试图出去,但提琴手只是立即报告一个关闭的连接。我的互联网工作得很好,如果我使用浏览器访问网址,则URL工作正常。有什么建议么?

+0

那可能对你有帮助。[link](http://stackoverflow.com/questions/6803666/c-sharp-httpwebrequest-hangs-program-suddenly-did-not-earlier)可能对你有所帮助。 – 2015-01-10 09:27:12

回答

1

我终于想通了这个问题。我发布这个答案的目的是为了希望它可以帮助其他人在未来不可避免的头部搔痒。

这是我现在的工作代码:

using (var requestStream = request.GetRequestStream()) 
{ 
    string content = "Email=" + Username + "&Passwd=" + Password; 
    requestStream.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetBytes(content).Length); 
} 
using (var sr = new StreamReader(request.GetResponse().GetResponseStream())) 
{ 
    string html = sr.ReadToEnd(); 
    string galxValue = ParseOutValue(html, "GALX"); 

    return GetLoginHtml2(galxValue, cookieJar); 
} 

我的猜测是,我的requestStream没有被垃圾收集,并得到响应流之前关闭。我认为响应流在请求流完成写入字节之前已打开并读取。在开始阅读之前,莫诺必须足够聪明才能完成写作。无论如何,它现在的工作,无论是Windows和Mono!愚蠢的.NET垃圾收集器。

相关问题