How to create an asynchronous method that is cancellable?

Asked

Viewed 99 times

3

How to create an asynchronous method that is cancellable?

In this context, the DoFoo() does things that cannot simply be stopped, like reading and writing files, and when canceling, I have to wait for those I/O operations to be completed for the method to be canceled.

private async void Button_Click()
{
    await DoFoo();
}

private async void Cancelar_Click()
{
    // cancelamento do método DoFoo()
    // ...
}

private async Task DoFoo()
{
    // operações de I/O
    File.WriteAllText("path", "conteudo");

    // operações de longa execução

    // ...
}
  • Depending on what you are running, you need to have the opportunity to perform the cancellation.

1 answer

5


Need to create a token method cancellation. You can only cancel what you are prepared to cancel. Generally speaking, the asynchronous . NET API accepts.

CancellationTokenSource cts;

private async void Button_Click() {
    cts = new CancellationTokenSource();
    try {
        await DoFoo(cts.Token);
    } catch (OperationCanceledException ex) {
        //trata o cancelamento
    }
}

private async void Cancelar_Click() => cts.Cancel();

private async Task DoFoo(CancellationToken ct) {
    // operações de I/O
    File.WriteAllText("path", "conteudo");
    for (var item in lista) {
        //faz o que quiser aqui
        ct.ThrowIfCancellationRequested(); //isto pode ser muito lento
    }
}

I put in the Github for future reference.

It is common not to check if there was request for cancellation in each step of the loop since the check has a reasonable cost, then you can filter when accepting a cancellation request, maybe every 1000 processed items, for example.

Certainly there are other ways to do depending on the goal. Exception does not need to be the treatment mechanism.

Documentation of CancellationTokenSource.

Documentation of CancellationToken.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.