Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 5: How to cancel a longrunning query in a async Task

In my application I have multiple tabs, displaying data from a database with Entity Framework 5.

When I switch between the tabs I start auto loading the data via a Task, because I don't want the GUI to become unresponsive (this task takes about 5-10 seconds):

public async void LoadData()
{
    [...]

    await Task.Run(
        () =>
            {
                Measurements = DataContext.Measurements
                                  .Where(m => m.MeasureDate = DateTime.Today)
                                  .ToList();
            });

    [...]
}

But while the task runs the user still can change to another tab, and if he does that I would like to cancel the EF query and/or the Task.

What would be the best way to accomplish this?

like image 405
Staeff Avatar asked Mar 22 '23 21:03

Staeff


1 Answers

In EF5, there is no way to cancel the queries since it doesn't accept CancellationToken. You can read more about this here: entity framework cancel long running query

However, EF6 does support it.

It has async version of all methods. So ToList() could instead be ToListAsync() for long running queries and it does have support for CancellationToken.

like image 81
TCM Avatar answered Mar 25 '23 21:03

TCM