Undo cancellation or expose cancellation method?

Which of the following two examples is preferable?

Example 1

public class Worker : IDisposable
{
    private CancellationTokenSource tokenSource;

    public string State { get; private set; }

    public async Task StartWorkAsync()
    {
        tokenSource = new CancellationTokenSource();

        this.State = "Working";
        await Task.Delay(5000, tokenSource.Token);
    }

    public void StopWork()
    {
        this.tokenSource.Cancel();
        this.State = "Stopped";
    }

    public void Dispose()
    {
        tokenSource?.Dispose();
    }
}

      

Example 2

public class Worker
{
    public string State { get; private set; }

    public async Task StartWorkAsync(CancellationToken ctoken)
    {
        ctoken.ThrowIfCancellationRequested();

        this.State = "Working";
        try
        {
            await Task.Delay(5000, ctoken);
        }
        catch (AggregateException) when (ctoken.IsCancellationRequested)
        {
            this.State = "Stopped";
        }
    }
}

      

Or perhaps both? However, my guess is that it expects common practice to cancel the cancellation with an async method.

+3


source to share


1 answer


You must accept CancellationToken

as an argument
and allow propagation OperationCanceledException

:



public async Task StartWorkAsync(CancellationToken ctoken)
{
  ctoken.ThrowIfCancellationRequested();

  this.State = "Working";
  try
  {
    await Task.Delay(5000, ctoken);
  }
  catch (OperationCanceledException)
  {
    this.State = "Stopped";
    throw;
  }
}

      

+4


source







All Articles