Skip to content

Added cancellation of requests using CancellationToken #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions CSharpHTTPClient/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web;
using System.Threading;

namespace SendGrid.CSharp.HTTP.Client
{
Expand Down Expand Up @@ -266,6 +267,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o

if( Enum.IsDefined(typeof(Methods), binder.Name.ToUpper()))
{
CancellationToken cancellationToken = CancellationToken.None;
string queryParams = null;
string requestBody = null;
int i = 0;
Expand All @@ -286,9 +288,13 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o
{
AddRequestHeader((Dictionary<string, string>)obj);
}
else if (name == "cancellationToken")
{
cancellationToken = (CancellationToken)obj;
}
i++;
}
result = RequestAsync(binder.Name.ToUpper(), requestBody: requestBody, queryParams: queryParams).ConfigureAwait(false);
result = RequestAsync(binder.Name.ToUpper(), requestBody: requestBody, queryParams: queryParams, cancellationToken: cancellationToken).ConfigureAwait(false);
return true;
}
else
Expand All @@ -304,22 +310,24 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o
/// </summary>
/// <param name="client">Client object ready for communication with API</param>
/// <param name="request">The parameters for the API call</param>
/// <param name="cancellationToken">A token that allows cancellation of the http request</param>
/// <returns>Response object</returns>
public async virtual Task<Response> MakeRequest(HttpClient client, HttpRequestMessage request)
public async virtual Task<Response> MakeRequest(HttpClient client, HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken))
{

HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
HttpResponseMessage response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
return new Response(response.StatusCode, response.Content, response.Headers);
}

/// <summary>
/// Prepare for async call to the API server
/// </summary>
/// <param name="method">HTTP verb</param>
/// <param name="cancellationToken">A token that allows cancellation of the http request</param>
/// <param name="requestBody">JSON formatted string</param>
/// <param name="queryParams">JSON formatted queary paramaters</param>
/// <returns>Response object</returns>
private async Task<Response> RequestAsync(string method, String requestBody = null, String queryParams = null)
private async Task<Response> RequestAsync(string method, String requestBody = null, String queryParams = null, CancellationToken cancellationToken = default(CancellationToken))
{
using (var client = new HttpClient())
{
Expand Down Expand Up @@ -367,9 +375,13 @@ private async Task<Response> RequestAsync(string method, String requestBody = nu
RequestUri = new Uri(endpoint),
Content = content
};
return await MakeRequest(client, request).ConfigureAwait(false);
return await MakeRequest(client, request, cancellationToken).ConfigureAwait(false);

}
catch(TaskCanceledException)
{
throw;
}
catch (Exception ex)
{
HttpResponseMessage response = new HttpResponseMessage();
Expand Down
30 changes: 25 additions & 5 deletions UnitTest/UnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net.Http;
using System.Text;
using System.Net;
using System.Threading;

namespace UnitTest
{
Expand All @@ -17,12 +18,19 @@ public MockClient(string host, Dictionary<string, string> requestHeaders = null,
{
}

public async override Task<Response> MakeRequest(HttpClient client, HttpRequestMessage request)
public override Task<Response> MakeRequest(HttpClient client, HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent("{'test': 'test_content'}", Encoding.UTF8, "application/json");
response.StatusCode = HttpStatusCode.OK;
return new Response(response.StatusCode, response.Content, response.Headers);
return Task.Factory.StartNew(() =>
{

HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent("{'test': 'test_content'}", Encoding.UTF8, "application/json");
response.StatusCode = HttpStatusCode.OK;

cancellationToken.ThrowIfCancellationRequested();

return new Response(response.StatusCode, response.Content, response.Headers);
}, cancellationToken);
}
}

Expand Down Expand Up @@ -74,5 +82,17 @@ public async void TestMethodCall()
var content = new StringContent("{'test': 'test_content'}", Encoding.UTF8, "application/json");
Assert.AreEqual(response.Body.ReadAsStringAsync().Result, content.ReadAsStringAsync().Result);
}

[Test]
[ExpectedException(typeof(TaskCanceledException))]
public async void TestMethodCallWithCancellationToken()
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();

var host = "http://api.test.com";
dynamic test_client = new MockClient(host: host);
Response response = await test_client.get(cancellationToken: cancellationTokenSource.Token);
}
}
}