I have a thread which calls one of the methods, now this method executes a query which can take a very long time possibly 40 minutes or so to complete,
I want to give user a a choice to be able to cancel this operation (meaning stop the thread and stop the query to release database).
I should mention that I am developing WPF Application using .net 4.5, SQL SERVER DB and C#.
If the UI thread is doing a Long-time operation it won't be able to process UI requests. This is also known as Not Responding. Use
ThreadPool
like this:To give user a choice to be able to cancel the operation use
CancellationTokenSource
like this:Note: in
LongTimeOperation
() you must have one more parameter of typeCancellationToken
This link is useful about
Cancellation
in Managed Threads.When you have your Thread blocked on waiting for the query, it's useless for stopping anything.
Make sure the SqlConnection of the query is accessible from your UI and Close it. Abandon the Thread, it will terminate (with an error you've got to suppress).
this is a common problem.But in
WPF
andWinForm
, i'd like to useBackGroundWorker
. See HereUsing Task Parallel Library (TPL) you can use the Task Cancellation pattern.
You should use backgroundworker, it is exactly what you want.
Eather drag and drop it from the toolbox or create it in code - behind. It supports Cancellation, reports progress, notifies when complete and know if it is running or not.
Here is an example.
A important things to look at: Never use resources in the
DoWork
method that are not created inside it. Thus pass things you need in the background worker as Arguments. And things that are created by the backgroundworker should not be set to a global variable ether, pass by result.When cancelling,
RunWorkCompleted
will also be fired. Now the query to the database is already being executed, so that is still running, even when your application lost all resources to it.To cancel that, we would need to know how you execute the query, like @S.Akbari mentioned is one way. Entity Framework 6 also supports cancellation.
For that: check this when using Queryable
here is another example
Or this solution without Entity Framework.