【问题标题】:GetRequestStream() freezes if there is no internet connection如果没有 Internet 连接,GetRequestStream() 将冻结
【发布时间】:2013-03-06 08:53:47
【问题描述】:

我已经成功生成了一个异步 Web 请求并为其设置了超时。但是,连接的设置仍在 UI 线程上,如果没有 Internet 连接,它似乎会冻结在 GetRequestStream 上。如何解决?

private WebRequest getPostLoginRequest (string username, string password)
{
    string postData = string.Format (@"<login><user>{0}</user><password>{1}</password></login>", username, password);
    byte[] buf = Encoding.UTF8.GetBytes (postData);

    var request = HttpWebRequest.Create (String.Format (@"{0}/auth/", baseServiceUrl));
    request.Method = "POST";
    request.ContentType = "application/xml";
    request.ContentLength = buf.Length;
    request.GetRequestStream ().Write (buf, 0, buf.Length);

    return request;
}

【问题讨论】:

  • 这将非常适合异步框架...好吧,当然,您将不得不创建一个不同的线程,并使用回调:)
  • 那么,如果您仍然必须创建一个新线程来启动它们,那么 BeginGetResponse 和 EndGetResponse 有什么用。我在哪里设置 GetRequestStream 的超时时间?
  • 好吧,在这种情况下使用BeginGetRequestStream

标签: c# mono webrequest


【解决方案1】:

HttpWebRequest.GetRequestStream() 创建到远程服务器的网络连接,因此它可以阻止 - 请改用 BeginGetRequestStream()

GetRequestStream () 的实现实际上只是对BeginGetRequestStream () / EndGetRequestStream() 的一个薄包装:https://github.com/mono/mono/blob/master/mcs/class/System/System.Net/HttpWebRequest.cs#L816

WebRequest.Create() 中没有任何可能阻塞的内容,因此从 UI 线程调用它是安全的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多