views:

294

answers:

3

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?

A: 

I'd say you'd probably need to run it on a separate Thread and cancel that instead.

Kieron
how can you cancel a thread?
Svish
I don't recommend going down this path. Using Thread.Abort is bad practice and does not even guarantee to abort the thread. See http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
Richard Szalay
yeah, I meant to have read something like that as well.
Svish
+1  A: 

If you set the CommandTimeout (seconds) property of DataContext, it will automatically throw an exception after the timeout elapses.

Richard Szalay
But can you set that while a query is running?
Svish
from a different thread?
Svish
No - you should set it before the command starts. I'm not sure what the defined behavior is to change it while a query is running.
Richard Szalay
yeah, but I don't want to kill a query at some random time. I want to kill it when the user asks for it to stop.
Svish
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.
Richard Szalay
So kind of just forget about it and let it finish in the background?
Svish
Yeah - I think that's your only choice. The only real downside is one less SQL connection until the query finishes.
Richard Szalay
exactly. but I guess that won't hurt too bad, since it won't be that much traffic anyways. I'm just looking for a way to let the user cancel it without having to wait a long time.
Svish
+1  A: 

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 an ThreadInterruptedException 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

Svish
I recommend against this solution. Using ThreadInterruptedException is just as bad as using Thread.Abort. I recommend reading the article I posted in my comment to Kieron's answer.
Richard Szalay
Maybe go into a loop and check a flag or something then? And then just return and not wait for the result if user want to cancel?
Svish