- Home /
Detecting network failure with IAsyncResult
I am currently sending HTTP web requests from Unity to web server using C#.
I wish to make all the POST requests to communicate asynchronously.
I've followed MSDN Guideline to implement asynchronous network communication with the web server.
The problem is that I am having a hard time detecting server failures such as network timeout or connection establishment failure due to invalid URI.
Here are code snippets that I've implemented at the moment:
protected void PostAsync(string uri, string jsonBody)
{
string fullUri = _uriPrefix + uri;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fullUri);
...
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request));
}
private void GetRequestStreamCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream requestStream = request.EndGetRequestStream(asyncResult);
requestStream.Write(asyncState.inputStream, 0, asyncState.inputStream.Length);
requestStream.Close();
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
When debugged using MonoDevelop, I found out that asyncResult parameter is of System.Net.WebAsyncResult instance which contains an exception indicating that the connection establishment was failed.
However, the problem is that I can't typecast the IAsyncResult asyncResult
instance to System.Net.WebAsyncResult
as such class does not seem to exist. (I've tried using System.net
)
When continued, my debugger does not go beyond request.EndGetRequestStream(asyncResult)
line. (Blocked)
Can anyone guide me on how I can detect connection establishment failure? Also, any other tips on how to handle such network failures would be greatly appreciated!
Thanks in advance,
Answer by Mulleteer · Jul 16, 2015 at 04:55 PM
You must wrap the call to EndGetRequestStream with try catch block.
try {
Stream requestStream = request.EndGetRequestStream(asyncResult);
...
} catch (WebException ex) {
Debug.Log("Connection failed", ex.Message);
}