我是新來的第三方物流。我正在使用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();
}