0Pricing
C# Academy · Lesson

Timeouts, IProgress<T>, async disposables (emulation)

Apply CancelAfter or Task.WhenAny-based timeouts, wire IProgress for UI-friendly updates, and use try/finally to emulate async cleanup in C# 6.

Plan

Aim:

  • Timeout with CancelAfter
  • Timeout via Task.WhenAny
  • Progress with IProgress<T>
  • Async cleanup pattern in C# 6 (try/finally)

Timeout via CancelAfter

Use CancelAfter and pass the token to the async API; the callee stops cooperatively on timeout.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
  static async Task<string> SlowOpAsync(CancellationToken ct)
  {
    // Simulate slow I/O that honors cancellation
    await Task.Delay(500, ct);
    return "OK";
  }

  public static void Main(string[] args)
  {
    var cts = new CancellationTokenSource();
    cts.CancelAfter(150); // timeout after 150 ms

    Task<string> t = SlowOpAsync(cts.Token);
    try
    {
      string result = t.GetAwaiter().GetResult(); // demo only
      Console.WriteLine(result);
    }
    catch (OperationCanceledException)
    {
      Console.WriteLine("Timed out");
    }
  }
}

All lessons in this course

  1. CancellationToken patterns; cooperative cancel
  2. Timeouts, IProgress , async disposables (emulation)
  3. Resilience basics: retry & backoff
← Back to C# Academy