简体   繁体   中英

Is Application.Restart bad?

I've got a .Net windows form application where a lot of variables are initialized in the Main_Load event and I have a situation where I want my DB re-queried and all vars set to null and re-initialized (basically the form 100% reloaded from the start), but I wrote my Main-Load in such a way (my fault) that it's not that easy to do...

I know I could get exactly what I want by simply calling Application.Restart and it does the trick beautifully , but I'm not sure if this is good programming practice or considered really bad.

Are there any problems that I'm likely to run into by using Application.Restart in this context?

Not friendly to debug, but there's nothing really wrong with it. It is the exact same as terminating the app and starting it again.

You can avoid it by simply creating a new instance of your main form and closing the old one. That however does require you to prevent the program from exiting. Code is here .

It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up.

Please follow this Thread

You can also do the job with

 System.Diagnostics.Process.Start(Application.ExecutablePath);
 Application.Exit();

To directly answer the question in the title, yes restarting an application to re-initialize variables is bad practice.

There are cases where restarting an application is usefull (in example self-update), but restarting to mimic a ReInitialize() method is bad in my opinion.

I had problems with this.

I really needed to restart a large Winforms Application, when a user logs off, to ensure all cached (my) data are purged.

Solved my problem by adding the Application.restart() into the Application Shutdown Event .

This works inside the VS environment and when running the EXE

If you want to find that event select your main project properties and from the Application (Side Tab) select View Application Events at the bottom.

My guess is that this works because it is very late on in the closing process. Hope this helps someone and, more importantly, it continues to work.

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