EF 5:如何在异步任务中取消朗读查询 [英] EF 5: How to cancel a longrunning query in a async Task
问题描述
在我的应用程序中,我有多个选项卡,使用Entity Framework 5从数据库显示数据。
In my application I have multiple tabs, displaying data from a database with Entity Framework 5.
当我在选项卡之间切换时,我开始自动加载数据任务,因为我不希望GUI无响应(这个任务需要5-10秒):
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();
});
[...]
}
但是任务运行用户仍然可以更改为另一个选项卡,如果他这样做,我想取消EF查询和/或任务。
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?
推荐答案
在EF5中,无法取消查询,因为它不接受的CancellationToken
。您可以在这里阅读更多信息:实体框架取消长时间运行的查询
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
但是,EF6确实支持它。
However, EF6 does support it.
它具有所有方法的异步版本。所以 ToList()
可以代替 ToListAsync()
长时间运行的查询,它确实支持 CancellationToken
。
It has async version of all methods. So ToList()
could instead be ToListAsync()
for long running queries and it does have support for CancellationToken
.
这篇关于EF 5:如何在异步任务中取消朗读查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!