Skip to content

Commit

Permalink
Merge pull request #3248 from esdrubal/web_request_abort
Browse files Browse the repository at this point in the history
[System] EndRead now throws WebException on abort.
  • Loading branch information
esdrubal committed Jul 13, 2016
2 parents 1172aac + 6f261e6 commit 725892b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mcs/class/System/System.Net/WebConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,8 @@ internal int EndRead (HttpWebRequest request, IAsyncResult result)
{
Stream s = null;
lock (this) {
if (request.Aborted)
throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
if (Data.request != request)
throw new ObjectDisposedException (typeof (NetworkStream).FullName);
if (nstream == null)
Expand Down
48 changes: 48 additions & 0 deletions mcs/class/System/Test/System.Net/WebRequestTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
//

using NUnit.Framework;
using MonoTests.Helpers;
using System;
using System.Net;
using System.Threading;
using System.Collections;
using System.Runtime.Serialization;
using Socks = System.Net.Sockets;
Expand Down Expand Up @@ -410,6 +412,52 @@ internal class TestWebRequest3 : WebRequest
{
internal TestWebRequest3 () { }
}

[Test] // Covers #41477
public void TestReceiveCancelation ()
{
var uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";

HttpListener listener = new HttpListener ();
listener.Prefixes.Add (uri);
listener.Start ();

try {
for (var i = 0; i < 10; i++) {
var request = WebRequest.CreateHttp (uri);
request.Method = "GET";

var tokenSource = new CancellationTokenSource ();
tokenSource.Token.Register(() => request.Abort ());

var responseTask = request.GetResponseAsync ();

var context = listener.GetContext ();
byte[] outBuffer = new byte[8 * 1024];
context.Response.OutputStream.WriteAsync (outBuffer, 0, outBuffer.Length);

Assert.IsTrue (responseTask.Wait (1000), "Timeout #1");

WebResponse response = responseTask.Result;
var stream = response.GetResponseStream ();

byte[] buffer = new byte[8 * 1024];
var taskRead = stream.ReadAsync (buffer, 0, buffer.Length, tokenSource.Token);

tokenSource.Cancel ();

Assert.IsTrue (taskRead.Wait (1000), "Timeout #2");

var byteRead = taskRead.Result;
}
} catch (AggregateException ex) {
var webEx = ex.InnerException as WebException;
Assert.IsNotNull(webEx, "Inner exception is not a WebException");
Assert.AreEqual (webEx.Status, WebExceptionStatus.RequestCanceled);
}

listener.Close ();
}
}

}
Expand Down

0 comments on commit 725892b

Please sign in to comment.