How to cancel an async query the right way

.net c# entity-framework entity-framework-6 wpf

Question

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?

Accepted Answer

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why