EF 5: How to Cancel a Longrunning Request in an Asynchronous Job

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?


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.