Wednesday, February 10, 2016

C# Cancel / abort an async method call/function with a web call as an example


Make the web method call.

string result = await MakeWebCall();

public async Task<string> MakeWebCall()
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.mysite.com");
    req.Method = WebRequestMethods.Http.Get;
    string result = null;

    try
    {
        using (WebResponse resp = await req.GetResponseAsync((ctGetResponse = new CancellationTokenSource()).Token))
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = await reader.ReadToEndAsync();
        }
    }
    catch (Exception ex)
    {
        return (ex.ToString());
    }
    return result;
}

Register the cancellationtoken

public static class Extensions
{
    public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
    {
        using (ct.Register((state) => ((HttpWebRequest)state).Abort(), request, false))
        {
            try
            {
                var response = await request.GetResponseAsync();
                return (HttpWebResponse)response;
            }
            catch (WebException ex)
            {
                // WebException is thrown when request.Abort() is called,
                if (ct.IsCancellationRequested)
                    // the WebException will be available as Exception.InnerException
                    throw new OperationCanceledException(ex.Message, ex, ct);
                // Abort not caled, throw the original Exception
                throw;
            }
        }
    }
}

Define the token globally

private CancellationTokenSource ctGetResponse;

call cancellation as required. In this example, its called when a link is clicked on the winform

private void linkLabelCancel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
            ctGetResponse.Cancel();
}

No comments:

Turn on Windows 11 Fast Boot

If windows starting is slow, to enable windows 11 fast startup/boot,  Press Windows + R, type powercfg.cpl, and hit Enter.  This will direct...