/// <summary> /// Raises the RequestCompleted event. /// </summary> /// <param name="e"></param> protected virtual void OnRequestCompleted(RequestCompletedEventArgs e) { try { if (Options.RequestComplete != null) { Options.RequestComplete(this, e.Response, e.Error, e.Cancelled); } if (RequestCompleted == null) { return; } RequestCompleted(this, e); } finally { if (mWait != null) { mWait.Set(); } } }
private WebHelperResponse MakeRequest_Internal() { // Make sure we have valid options. if (Options == null) { Options = new WebHelperOptions(); } CancellationPending = false; WebHelperResponse whResponse = null; try { HttpWebRequest request = null; bool sent = false; var parameters = new WebParameters(Options.Values); using (var contentType = ContentType ?? ContentType.CreateContentType(Options.Method, parameters)) { request = CreateRequest(contentType); sent = contentType.SendRequest(this, request); } RequestCompletedEventArgs completedArgs = null; if (!sent) { if (!CancellationPending) { throw new InvalidOperationException("Unable to complete request. Unknown error."); } completedArgs = new RequestCompletedEventArgs(Options.State, true); } else { using (var response = (HttpWebResponse)request.GetResponse()) whResponse = ProcessResponse(response); // even if a cancellation is pending, if we recieved the response, complete the request as normal. if (whResponse != null) { completedArgs = new RequestCompletedEventArgs(whResponse, Options.State, false); } else if (CancellationPending) { completedArgs = new RequestCompletedEventArgs(whResponse, Options.State, true); } else { throw new InvalidOperationException("Unable to receive response. Unknown error."); } } Post((arg) => { OnRequestCompleted((RequestCompletedEventArgs)arg); }, completedArgs); } catch (Exception ex) { var completedArgs = new RequestCompletedEventArgs(ex, Options.State, false); Post((arg) => { // Regardless of the outcome, RequestCompleted is guaranteed to be raised. // Caller is responsible for checking the status of the request object to // see if it is successful or not. OnRequestCompleted((RequestCompletedEventArgs)arg); }, completedArgs); if (mAsyncOperation == null) { // Don't throw the exception if running on a thread. It can't be caught // and makes it difficult to debug (cannot continue in Visual Studio). throw; } } finally { if (mAsyncOperation != null) { using (var done = new ManualResetEvent(false)) { // Use the ManualResetEvent to ensure that the operation completes before // we exit the method. // This is used to ensure that the Wait method will not continue until // after the final operation has been completed. mAsyncOperation.PostOperationCompleted((arg) => { mAsyncOperation = null; done.Set(); }, null); done.WaitOne(); } } } return(whResponse); }