views:

112

answers:

2

Hi,

I have a task running in backgroundworker. on clicking the start button user starts the process and have got one cancel button to cancel the processing.

When user clicks on cancel, I would like to show a message box that "Process has not been completed , do you want to continue".

Here I want the processing which is left to be done only after user input. Till then want to halt the back ground thread. Can anyone help me on this. Is there anyway to halt the background worker for some time .Any kind of help will be appreciated.

+5  A: 

Not built in. You could tell your code to (on every [n] loop iterations, etc) check something like a ManualResetEvent to see if it should keep running (at the same time it checks for cancellation). I don't recommend suspending the thread (Thread.Suspend), since you don't know what locks etc it may hold at the time.

On the other hand... why not let it run until you know it should be cancelled? Then you just need to check for cancellation (there is a flag for this) every [n] iterations...

Marc Gravell
Perhaps the processing is CPU intensive and the programmer wants to temporarily return resources to the user while he makes his decision.
Jonathan Allen
Or the background process is doing something irreversible (removing files, etc.), which should be interrupted *quickly* if started accidentally.
Heinzi
+1  A: 

If the BackgroundWorker is working on an object that is visible to both threads, you could 'lock' that object while waiting for the user to answer the question in a dialog box. This will cause the worker's thread to halt until the dialog-generating thread ends the lock.

Assaf
That would only block the worker if the worker thread continually attempts to acquire the lock and releases it. And it could lead to the **UI** getting blocked if the worked *doesn't* release it each time.
Marc Gravell
Right, it will depend on the way the worker uses the object (when/if the lock is acquired/released). But a new 'dummy' shared object could be used if no existing object's is treated as per the conditions stated above (in post and comment).
Assaf