C #: Is it possible to cancel a linq2sql request?

Can I cancel a linq2sql request? For example, if I created a request that takes time to run, I would like the user to be able to cancel it. Anyone have any good ideas on this?

+4
source share
4 answers

So, according to Richard Salay comment:

Itโ€™s best to run the request in the background thread and simply unsubscribe from the events of the container object when the user clicks โ€œCancelโ€.

And I think I agree that this is normal now. I would like to see some Async query features already in the framework, but until this happens, it should do so.

Have not started to implement this yet (you need to finish some other things first), but one of the ways it works:

  • In a workflow, execute queries in a separate query thread, and then join that thread until it is completed.
  • When the user clicks on cancel, call the Interrupt method of the workflow, which will then receive a ThreadInterruptedException and stop waiting for the request flow to complete.

May add code later when I create it. But let's see how it turns out: p

+2
source

If you set the CommandTimeout (seconds) property of the DataContext , it automatically throws an exception after a timeout.

+2
source

I know this answer is quite late, but here is how I do it:

 class Program { public class Person { public string Name; public int Age; } public static void ExecuteQueryAsync ( IEnumerable<Person> collectionToQuery , Action<List<Person>> onQueryTerminated , out Action stopExecutionOfQuery ) { var abort = false; stopExecutionOfQuery = () => { abort = true; }; Task.Factory.StartNew( () => { try { var query = collectionToQuery.Where( x => { if ( abort ) throw new NotImplementedException( "Query aborted" ); // query logic: if ( x.Age < 25 ) return true; return false; } ); onQueryTerminated( query.ToList() ); } catch { onQueryTerminated( null ); } }); } static void Main ( string[] args ) { Random random = new Random(); Person[] people = new Person[ 1000000 ]; // populate array for ( var i = 0 ; i < people.Length ; i++ ) people[ i ] = new Person() { Age = random.Next( 0 , 100 ) }; Action abortQuery; ExecuteQueryAsync( people , OnQueryDone , out abortQuery ); // if after some time user wants to stop query: abortQuery(); Console.Read(); } static void OnQueryDone ( List<Person> results ) { if ( results == null ) Console.WriteLine( "Query was canceled by the user" ); else Console.WriteLine( "Query yield " + results.Count + " results" ); } } 
0
source

I would say that you probably need to run it on a separate thread and cancel it.

-1
source

All Articles