简体   繁体   English

取消主窗体关闭,同时在后面运行一些线程,C#.windows应用程序?

[英]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. 我正在运行一个后台线程来在Windows应用程序中移动一些配置文件数据。 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. 如果我在“ Form_Closing”事件中执行此操作,则线程停止(在调试时),并且控件停留在表单本身中。 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: Closing事件窗体中,可以使用Cancel属性:

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. 如果您对表单中的线程有引用,则可以在OnFormClosing事件中检查其IsAlive属性。 If it is true then prevent the form from close by e.Cancel = !Thread.IsAlive 如果为true,则通过e.Cancel =!Thread.IsAlive阻止表单关闭

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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