Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel an async query the right way

This is a follow up question to this question.

I'm trying to load data from my database which will take 5-10 seconds, but I want the GUI to stay responsive and also it should be cancellable.

private CancellationTokenSource _source;

public IEnumerable<Measurement> Measurements { get { ... } set { ... } }

private async void LoadData()
{
    _source = new CancellationTokenSource();

    using (var context = new TraceContext())
    {
        Measurements = null;
        Measurements = await context.Measurements.ToListAsync(_source.Token);
    }
}

private void Cancel()
{
    if (_source != null)
        _source.Cancel();
}

public RelayCommand ReloadCommand
{
    get { return _reloadCommand ?? (_reloadCommand = new RelayCommand(Reload)); }
}
private RelayCommand _reloadCommand;

public RelayCommand CancelCommand
{
    get { return _cancelCommand ?? (_cancelCommand = new RelayCommand(Cancel)); }
}
private RelayCommand _cancelCommand;

I've tried a few things, but I just can't get this to work properly, this just loads the List and thats all, I can't cancel this.

Where is the error in this?

like image 672
Staeff Avatar asked Aug 06 '13 11:08

Staeff


People also ask

How do I end async method?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

How to cancel cancellation token c#?

If you go to the definition of the CancellationToken class, then you will see that this class has one property called IsCancellationRequested which returns true if the cancellation has been requested for this token; otherwise, false. If it returns true then we need to stop the execution and return.

How does a cancellation token work?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.


1 Answers

Thanks for bringing this up. Currently the implementation of this async API in EF relies on the underlying ADO.NET provider to honor cancellation, but SqlDataReader.ReadAsync has some limitations and we have observed that in many cases it won't cancel immediately when cancellation is requested. We have a bug that we are considering for fixing in EF6 RTM that is about introducing our own checks for the cancellation requests between row reads inside the EF methods.

In the meanwhile you can workaround this limitation by using ForEachAsync() to add items to the list and check on every row, e.g. (not thoroughly tested):

    public async static Task<List<T>> MyToListAsync<T>(
        this IQueryable<T> source,
        CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        var list = new List<T>();
        await source.ForEachAsync(item =>
        {
            list.Add(item);
            token.ThrowIfCancellationRequested();
        });
        return list;
    }
like image 57
divega Avatar answered Sep 28 '22 02:09

divega