[英]entity framework cancel long running query
我是TPL的新手。 我正在使用TPL對數據庫進行一些異步調用。 GetDocumentAsync方法下面被多次調用,並且在卸載不同線程上的任務時做得很好,以保持UI線程的響應。
這里有兩個目標:1)保持UI線程響應2)讓用戶能夠中止請求。
我已設法中止請求但是我無法中止Entity框架已經放入數據庫並且查詢在db級別運行的請求..或者它甚至還沒有啟動。
因此,GetDocuments方法仍然返回已取消任務的文檔。
有沒有我可以中止來自EF的請求? 我可以在實施中做得更好嗎?
Entities _context = new Entities();
CancellationTokenSource _tokenSource = new CancellationTokenSource();
public async void GetDocumentsAsync(string userName)
{
IList<Document> results;
try
{
results = await
Task<List<Document>>.Factory.StartNew(() =>
{
_tokenSource.Token.ThrowIfCancellationRequested();
return GetDocuments(userName);
}, _tokenSource);
}
catch (OperationCanceledException ex)
{
Debug.WriteLine(string.Format("Task canceled for user {0} on thread", userName ));
}
if(!_tokenSource.IsCancellationRequested)
{
// results is used to update the UI
}
}
public void Abort()
{
_tokenSource.Cancel();
}
public List<Document> GetDocuments(string userName)
{
//I am using the connected model and need to use the Context for change tracking and other goodies..
var query = from c in _context.Documents
where c.CreatedBy == userName
select c;
query = query.Take(50); // I want to be able to cancel this query. Can this be done ???
return query.ToList();
}
異步支持是即將推出的EF6的一部分。
查看KSA的相關博客文章以獲取概述。
http://odetocode.com/Blogs/scott/archive/2012/08/26/async-in-entity-framework-6-0.aspx
有了它,您將使用取消令牌切換到ToListAsync。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.