Is it possible to cancel a linq2sql query? Like if I have built a query that takes a while to run, I would like it to be possible for the user to cancel it. Does anyone have any good ideas on this?
I'd say you'd probably need to run it on a separate Thread and cancel that instead.
If you set the CommandTimeout (seconds) property of DataContext, it will automatically throw an exception after the timeout elapses.
So, according to Richard Szalay's comment:
Your best bet is to run the query in a background thread and simply unsubscribe from the container object's events when the user hits Cancel.
And I think I agree that this is a an ok work-around for now. What I would love to see is some Async query functionality already in the framework, but until that happens this will have to do.
Haven't started to implement this yet (have to finish some other things first), but one way it could work:
- In the working thread, do the queries in a separate query thread and then Join that thread until it is finished.
- When user hits cancel, call the
Interrupt
method of the working thread, which would then get anThreadInterruptedException
and stop waiting for the query thread to finish.
May add some code later when I make it. But we'll see how pretty it turns out :p