簡體   English   中英

HttpWebRequest導致應用程序掛起

[英]HttpWebRequest causes application to hang

我有一個奇怪的問題。 我在Visual Studio 2013中創建了一個應用程序,該應用程序在Windows中運行良好。 然后,我將其移植到Mono,因為我需要該應用程序在Linux控制台中運行。

該應用程序在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);
        }
    }
}

我評論了線路的懸掛位置。 我茫然為什么至少沒有給我超時錯誤。 我運行了提琴手,發現它試圖退出,但是提琴手只是立即報告已關閉連接。 如果使用瀏覽器訪問,我的Internet正常運行,URL正常運行。 有什么建議么?

我終於弄明白了這個問題。 我正在發布此答案,希望它可以在將來對某些不可避免的頭部刮傷有所幫助。

現在是我的工作代碼:

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進行垃圾收集和關閉。 我認為響應流在請求流完成其字節寫入之前就處於打開和讀取狀態。 Mono必須足夠聰明才能在開始閱讀之前完成寫作。 無論如何,它現在可以在Windows和Mono中運行! 愚蠢的.NET垃圾收集器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM