I have a backgroundworker that is running.

The problems comes when you press the closebutton on the form in the upper right corner. This makes the form stuck completely.
The problem is that the Worker doesn´t get a chance to finish and return the backgroundWorker1_RunWorkerCompleted event.

How can I come around this problem. I try to put:

Application::Exit() in the Form Closing event but that doesn´t work either.

In main thread:
When you handle the close event send a message to the worker thread requesting termination. Then use WaitForSingleObject() on the worker thread handle to wait for thread termination.

In the worker thread:
Handle your termination message and stop the thread.

Sorry, only just seen your previous thread on this topic which makes it clearer that you're using .NET. In that case my earlier post isn't going to be very helpful.

You can use CancelAsync() as you mentioned in the other thread, just make sure you're checking the CancellationPending property in the worker. Just calling CancelAsync() isn't sufficient to stop the thread - it needs to be terminated gracefully in the thread itself.

To be honest I am not sure what is happening. It seems that my backgroundworker is ready but the form only get stuck when I close the form with the button (x) in the upperright corner but not when I do:

this->close(); in the menu of the application. I perheps will open a new thread how to disable the (X) button.

Thank you anyway for your help...

Sorry, only just seen your previous thread on this topic which makes it clearer that you're using .NET. In that case my earlier post isn't going to be very helpful.

You can use CancelAsync() as you mentioned in the other thread, just make sure you're checking the CancellationPending property in the worker. Just calling CancelAsync() isn't sufficient to stop the thread - it needs to be terminated gracefully in the thread itself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.