Skip to content

Cancelling Requests

dkackman edited this page Oct 11, 2014 · 1 revision

While using the DynamicRestClient cancellation is supported by passing a CancellationToken as one of the unnamed arguments to a request method.

[TestMethod]
public void Cancel()
{
    dynamic client = new DynamicRestClient("http://dev.virtualearth.net/REST/v1/");

    string key = CredentialStore.RetrieveObject("bing.key.json").Key;

    using (var source = new CancellationTokenSource())
    {
        // run request on a different thread and do not await thread
        Task t = client.Locations.get(source.Token, postalCode: "55116", countryRegion: "US", key: key);
            
        // cancel on unit test thread
        source.Cancel();

        try
        {
            // this will throw
            Task.WaitAll(t);
            Assert.Fail("Task was not cancelled");
        }
        catch (AggregateException e)
        {
            Assert.IsTrue(e.InnerExceptions.OfType<TaskCanceledException>().Any());
        }
    }
}

Clone this wiki locally