简体   繁体   中英

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?

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;
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM