如果没有互联网连接,GetRequestStream()会冻结

时间:2013-03-06 08:53:48

标签: c# mono webrequest

我设法产生异步webrequest并为它设置超时。但是,连接的设置仍然在UI线程上,如果没有互联网连接,它似乎会冻结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;
}

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题