Dhanapal
Dhanapal

Reputation: 14507

Cancel Main Form closing while some thread runs in back, C# .windows application?

I am running a background thread to move some profile data in an windows application. This thread will run priodically on certain interval.

If the user tries to close the form while the thread runs, i should prompt the user about the thread running and should not allow the user to close form. Once its (thread) completed, then only i have to close the form.

If i do it in the 'Form_Closing' event, thread stops (when i debug) and the control stays in the form itself. After closing the form, thread resumes.., not sure of any issues.

How do i effectly handle this?

Upvotes: 0

Views: 921

Answers (2)

Slava Kovalchuk
Slava Kovalchuk

Reputation: 523

If you have a reference to the thread in your form, you can in OnFormClosing event check its IsAlive property. If it is true then prevent the form from close by e.Cancel = !Thread.IsAlive

Upvotes: 0

ionden
ionden

Reputation: 12776

In the form Closing event you could use the Cancel property:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
        if (backgroundWorker1.IsBusy) {
            MessageBox.Show("Thread busy!");
            e.Cancel = true;
        }
    }

Upvotes: 1

Related Questions