Search code examples
c#asynchronouscancellation

Cancel a library async method like Dns.GetHostEntryAsync()


Is it possible to cancel an async library method like Dns.GetHostEntryAsync() ?

I have hundreds of these tasks running in parallel (DNS blacklist lookups) and every now and then I need to cancel the entire list of tasks.

Example:

List<Task<IPHostEntry>> tasks = new List<Task<IPHostEntry>>();
foreach (string s in BlackLists)
{
    tasks.Add(Dns.GetHostEntryAsync(s));
}

Edit: This question is about library async methods which does not take a CancellationToken.


Solution

  • While it is possible to cancel some async Library method, it is not possible for Dns.GetHostEntryAsync as you can't provide a CancellationToken to it.

    For more information about how to cancel an async method that support cancellation, see Cancellation in Managed Threads.

    var cts = new CancellationTokenSource();
    //Task.Delay allows me to provide a cancellation token
    var task = Task.Delay(new TimeSpan(1, 0, 0), cts.Token);
    cts.Cancel();
    try
    {
      await task;
    }
      catch (OperationCanceledException)
    {
      Console.WriteLine("Cancelled");
    }