Note that there are some explanatory texts on larger screens.

plurals
  1. POentity framework cancel long running query
    text
    copied!<p>I am new to the TPL. I am using the TPL to make some async calls to the database. Below the GetDocumentAsync method is called multiple times and do a good job at offloading the task on a different thread to keep the UI thread responsive. </p> <p>There are two objectives here: 1) Keep the UI Thread Responsive 2) Give the user the ability to abort the request. </p> <p>I have managed to abort the request however i am unable to abort the request that Entity framework has already put to the database and the query is running at the db level.. or perhaps it has not even started. </p> <p>Therefore the GetDocuments method still returns the documents on the canceled tasks. </p> <p>Is there a away i can abort the request from the EF?? Can i do anything better in my implementation ?? </p> <pre><code> Entities _context = new Entities(); CancellationTokenSource _tokenSource = new CancellationTokenSource(); public async void GetDocumentsAsync(string userName) { IList&lt;Document&gt; results; try { results = await Task&lt;List&lt;Document&gt;&gt;.Factory.StartNew(() =&gt; { _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&lt;Document&gt; 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(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload