2017-07-22 4 views
3

Welches der folgenden zwei Beispiele wird bevorzugt?Nehmen Sie ein Cancellingtoken oder legen Sie eine Methode für die Stornierung offen?

Beispiel 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(); 
    } 
} 

Beispiel 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"; 
     } 
    } 
} 

Oder vielleicht einfach beides? Allerdings gehe ich davon aus, dass es üblich ist, ein cancellationtoken mit einer asynchronen Methode zu verwenden.

Antwort

4

You should accept a CancellationToken as an argument und lassen Sie die OperationCanceledException propagieren:

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

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