Canceling a task and handling timeouts

Timeouts

You can set the desired timeout value (miliseconds) in the WebApiClientOptions object or creating a CancellationToken. When the timeout limit is reached, an exception is thrown. Let's see both ways of doing that. First example is using a WebApiClientOptions object:

try
{
	WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants") { Timeout = 100 };
		
	using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
	{
		var rest = await client.GetOneAsync(1);
	}
}
catch (WebApiClientException e)
{
	Assert.AreEqual(HttpStatusCode.RequestTimeout, e.StatusCode);
}

And using a CancellationToken:

try
{
	WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");
		
	using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
	{
		CancellationTokenSource src = new CancellationTokenSource(100);
		
		var rest = await client.GetOneAsync(1, src.Token);
	}
}
catch (WebApiClientException e)
{
	Assert.AreEqual(HttpStatusCode.RequestTimeout, e.StatusCode);
}

Cancelling a task

An asynchronous operation can be canceled at any time if we're using a CancellationToken. But instead of throwing an WebApiClientException, it throws a AggregateException. Here is an example:

try
{
	WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");
		
	using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
	{
		CancellationTokenSource src = new CancellationTokenSource(100);
		
		Task<Restaurant> task = client.GetOneAsync(1, src.Token);
		src.Cancel();
		task.Wait();
		Assert.IsNull(task.Result);
	}
}
catch (AggregateException e)
{
	e.Handle(ex =>
	{
		if (ex is WebApiClientException)
		{
			var timeoutException = ex as WebApiClientException;

			Assert.AreEqual(HttpStatusCode.RequestTimeout, timeoutException.StatusCode);

			return true;
		}

		Assert.Fail(ex.Message);

		return false;
	});
}