After closing the form, the process is still running and the issue is reproduced and resolved

Source: Internet
Author: User

1 Problem Statement

In development, you encounter such a problem:

When you close the application by tapping the fork in the upper-right corner of the program main form, the program's process is not closed.

By accessing the information, we understand that there are two main reasons for such problems:

1) There is a dead loop in the program.

2) The program is a multithreaded program, and after the form is closed, the thread is still working.

This article will reproduce and propose a solution for this type of problem.

2 scene rendition

@ Scene 1

New Windows application closewindowexp, the program changes the background color of the form every second.

The effect after the program is running, as shown (the process of change, please imagine it in your mind).

The main code of the program is shown below.

//******** Form close problem Sample code////Author: March or May child////date:2014/07/27////http:/ /blog.csdn.net/yl2isoft////************************************************************ using System;using System.drawing;using system.threading;using System.Windows.Forms;        namespace closewindowexp{public partial class Frmcase1:form {Random rand = new Random ();        Public FrmCase1 () {InitializeComponent ();                private void Button1_Click (object sender, EventArgs e) {while (true) { int C1 = rand.                Next (0, 244); int c2 = rand.                Next (0, 244); int c3 = Rand.                Next (0, 244); This.                BackColor = Color.FromArgb (C1,C2,C3);                Application.doevents ();            Thread.Sleep (1000); }        }    }}
Code, the work of changing the background color of the form every second through a while loop, in which three integers are randomly generated in each iterationC1,C2,C3, and use these three integers to generate the background color of the form, followed by aApplication.doevents () method, use this method to ensure that even if the form is reflected in the loop (or if you remove it and see what it will do), the end of each loop will cause the program to sleep a little (1s), so that the interval of color changes can be approximately around 1s clock.

Run the program and then click the cross in the upper right corner of the form to close the form (is to close the form oh, I have always thought that closed the form also closed the program, it appears that this is not correct), then open the Task Manager, open the "process" item, in the list to find closewindowexp the figure, very unfortunate, found, please look.

@ Scene II

Scenario two gives the example to do the same thing as an example of a scenario, just moving the work to a new worker thread.

The following is the main code for the scenario two example.

Form close problem Sample code////Author: March or May child////DATE:2014/07/27 Http://blog.csdn.net/yl2isoft////************************************************************using System; Using system.drawing;using system.threading;using System.Windows.Forms;        namespace closewindowexp1{public partial class Frmcase2:form {Random rand = new Random ();        Public FrmCase2 () {InitializeComponent ();            } private void Button1_Click (object sender, EventArgs e) {Thread t = new Thread (() = = {if (this. invokerequired) {this.                            Invoke (new Action () = {while (true) { int C1 = rand.                            Next (0, 244); int c2 = rand.                            Next (0, 244); int c3 = Rand.                            Next (0, 244); This. BackcOlor = Color.FromArgb (c1, C2, C3);                            Application.doevents ();                        Thread.Sleep (1000);                }                    }));            }            });        T.start (); }    }}

In fact, for the example given in scenario two here, I am not at ease, for fear of using it does not give a good description of what I want to express, because in essence he is no different from the example, because there is a dead loop in the program that causes the problem to occur.

In studying the causes of such problems, we can think of this, when the form is closed, why the program is still running, it must be because the program has not finished the work, of course, this job may be finished in a few minutes, it may never be done (dead cycle), as to who did this work is the main thread, or work threads, there is no difference in nature. This is precisely illustrated by the two examples we give, because the work of instance one is done in the main thread, and the work of instance two is done in the worker thread. However, either the main thread or the worker thread, as long as there is unfinished work that can cause this type of problem to occur. So, the reason for this kind of problem boils down to one point: When you close a form, the process is not ended as long as the thread is still working.

In actual development, we often use a worker thread to do some repetitive work, so in multithreaded development, it is more likely to have a dead loop or close a form that needs to work for a while. Therefore, it is more important to pay attention to the occurrence of this kind of problem in multithreading development.

Find the reason, solve the problem is simple. for this type of problem resolution, just make sure that no threads are working after the form is closed . The specific solution may be subject to availability.

3 workaround

@ Method 1

Modify the Loop condition while (true) to the while (this. Visible).

This way, when the form closes, the Visible property value of the form becomes false, and the while loop is terminated, and the process ends normally.

@ Method 2

In the form's FormClosing event handling method, use code System.Environment.Exit (0) to force the exit of the current process so that it will end regardless of whether the thread is still working under the process.

private void Frmcase2_formclosing (object sender, FormClosingEventArgs e) {     System.Environment.Exit (0);}
The principle of Method 1 is to end the thread by ending the dead loop in the program, so that the process can end normally, and Method 2 is not to force the thread to close all threads and then gracefully end the process.

We are not going to discuss which method is better, just to give a description of the direction of thinking that solves such a problem: to ensure the normal end of the process by ending the work of all threads . This is, of course, a subject of this article.

Well, it's written here, I hope not to digress.

Extended reading:

Summary of C#-winform Exit method

Detail UI threads and Windows Message Queuing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.