I can't stop UI thread when i use HttpWebRequest and HttpWebResponse also it will hang when it cal WaitOne()
void method1()
{
url = "http://192.168.5.22/mobile/testpost.php" ;
request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
//// request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
RequestState myRequestState = new RequestState();
myRequestState.Request = request;
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), myRequestState);
event_2.WaitOne();
String s = myRequestState.responseAsString;
String g = s;
}
private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
{
RequestState myrequestobj = (RequestState)AsyncResult.AsyncStat开发者_StackOverflow社区e;
HttpWebRequest myrequest = myrequestobj.Request;
response = (HttpWebResponse)myrequest.EndGetResponse(AsyncResult);
string test1;
test1 = ((HttpWebResponse)response).StatusDescription;
if (response.StatusCode == HttpStatusCode.OK)
{
// Create the stream, encoder and reader.
Stream responseStream = response.GetResponseStream();
var x =response.GetResponseStream();
//Encoding streamEncoder = Encoding.UTF8;
StreamReader responseReader = new StreamReader(responseStream);
responseAsString = responseReader.ReadToEnd();
myrequestobj.responseAsString = responseAsString;
}
else
{
throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
}
event_2.Set();
}
HttpWebRequest methods seem to be delegating part of their work to the UI thread. Here is a part of a stack trace from a deadlock situation I had:
...
System.Windows.dll!System.Net.Browser.AsyncHelper.BeginOnUI(System.Net.Browser.BeginMethod beginMethod, System.AsyncCallback callback, object state) + 0x9b bytes
System.Windows.dll!System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(System.AsyncCallback callback, object state) + 0x25 bytes
...
Note the BeginOnUI after the BeginGetResponse. The 'asynchronous' callback is actually synchronized with the UI thread and therefore hangs when the UI thread is blocked. HttpWebResponse methods might be doing the same kind of synchronization.
精彩评论