How do I restart my C# WinForm Application?
Asked Answered
K

24

102

Developing a C# .NET 2.0 WinForm Application. Need the application to close and restart itself.

Application.Restart();

The above method has proven to be unreliable.

What is a better way to restart the application?

Kacerek answered 22/4, 2009 at 21:52 Comment(8)
I'm curious about the need to restart your app. I've never thought about that need before What are your circumstances?Malayalam
Our particular circumstance - a media player application which is supposed to run through some images and flash content in a loop. Should run for days and days without a machine restart, and there is no keyboard/mouse so no user interaction. If the program crashes (unhandled exception), need to restart the program, not exit out or display an error. #774268 See that for why the program keeps having exceptions I can't prevent. :(Kacerek
In the end, a much better solution for our application was to develop a small Watchdog application that gets started (if not running already) from the main application. The watchdog simply checks every 10 seconds or so to see if the main application still has a process running, and if it doesn't, it starts one. Simple, elegant, and much sturdier than trying to restart from the main app.Kacerek
Another reason for restart is when you change language or have downloaded an update.Eiffel
But what if... The watchdog application crashes?Amarelle
@Amarelle I suppose you could have your main application watch for that condition and restart it. Sort of a symbiotic relationship. The reality of it is, though, that your watchdog app should be so simple that it's odds of crashing (or being closed accidentally?) are much, much smaller.Kacerek
@AdamNofsinger Oh right, that would probably work! Cool :)Amarelle
Some malware/spyware uses a pair of programs that monitor each other and/or registry entries to remain running. They can be difficult to kill...Marcionism
F
42

Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..."

This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.)

This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck.

Edit: Using a 2nd application works. All I did in the second app was:

    static void RestartApp(int pid, string applicationName )
    {
        // Wait for the process to terminate
        Process process = null;
        try
        {
            process = Process.GetProcessById(pid);
            process.WaitForExit(1000);
        }
        catch (ArgumentException ex)
        {
            // ArgumentException to indicate that the 
            // process doesn't exist?   LAME!!
        }
        Process.Start(applicationName, "");
    }

(This is a very simplified example. The real code has lots of sanity checking, error handling, etc)

Forestforestage answered 9/9, 2009 at 3:22 Comment(5)
I agree with HiredMind, and I actually went with the same "Watchdog program" implementation myself shortly after writing the answer. Sorry, should have come back here and updated. I wouldn't think it should feel too horribly ugly/yucky/dirty. The Watchdog program pattern is pretty widely used.Kacerek
You don't actually need a second application on disk... you could use a script and generate it on the fly with a temporary name... I think this may alleviate your sense of guilty having a second application for the sake of restarting your own... Or you could "emit" an entire C# application, compile it, save it to disk and execute it (dirty, dirty thinking)..Geordie
The first paragraph is not correct: Process.Start does not look at the list of running OS processes. This documentation statement only talks about that object instance of the Process class. The Process class can be attached to a running process but it can also be in an unstarted state. In my opinion this is a design screw up. The best practice, IMO, is to never reuse a Process instance and to immediately start it after creation. Ideally, use the static Process.Start method. Then, this documentation and design flaw never come into play.Leaky
The code shown here is also unreliable because of WaitForExit(1000). But the entire waiting is not necessary to start a new process. It might be additional behavior that you want, but it's not required to start a new process.Leaky
I don't know about now, but nine years ago (ahem) this was definitely correct. :-)Forestforestage
T
108

A much simpler approach that worked for me is:

Application.Restart();
Environment.Exit(0);

This preserves the command-line arguments and works despite event handlers that would normally prevent the application from closing.

The Restart() call tries to exit, starts a new instance anyway and returns. The Exit() call then terminates the process without giving any event handlers a chance to run. There is a very brief period in which both processes are running, which is not a problem in my case, but maybe in other cases.

The exit code 0 in Environment.Exit(0); specifies a clean shutdown. You can also exit with 1 to specify an error occurred.

Tuyere answered 23/2, 2011 at 3:8 Comment(3)
Simple, yet reliable. This should be the accepted answer. I was trying to implement a sign-out feature that would empty all global variables and appear as if the application just started. I was going to just show the panel for logging in and reset all global variables that hold important info from DB to nothing. This made life a lot more simple. Thanks!Persistence
System.Windows.Forms.Application.Restart() also works for WPF applications. Tested with Windows 10 OS.Postconsonantal
Whaaaat?! You kiddin ... right? C# <3. Have in mind, this by default won't raise OnClose() form events and similar.Nahama
P
58

If you are in main app form try to use

System.Diagnostics.Process.Start( Application.ExecutablePath); // to start new instance of application
this.Close(); //to turn off current app
Plugboard answered 17/9, 2010 at 16:47 Comment(3)
It is similar, but different. Application.Exit didn't work form me, and this.Close() did the job.Plugboard
May Enviorment.Exit(0) will also do the job.Guenevere
Enviorment.Exit is a dirty and quite invasive exit because it prevents application cleanup code from running. Not the right choice most of the time.Leaky
F
42

Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..."

This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.)

This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck.

Edit: Using a 2nd application works. All I did in the second app was:

    static void RestartApp(int pid, string applicationName )
    {
        // Wait for the process to terminate
        Process process = null;
        try
        {
            process = Process.GetProcessById(pid);
            process.WaitForExit(1000);
        }
        catch (ArgumentException ex)
        {
            // ArgumentException to indicate that the 
            // process doesn't exist?   LAME!!
        }
        Process.Start(applicationName, "");
    }

(This is a very simplified example. The real code has lots of sanity checking, error handling, etc)

Forestforestage answered 9/9, 2009 at 3:22 Comment(5)
I agree with HiredMind, and I actually went with the same "Watchdog program" implementation myself shortly after writing the answer. Sorry, should have come back here and updated. I wouldn't think it should feel too horribly ugly/yucky/dirty. The Watchdog program pattern is pretty widely used.Kacerek
You don't actually need a second application on disk... you could use a script and generate it on the fly with a temporary name... I think this may alleviate your sense of guilty having a second application for the sake of restarting your own... Or you could "emit" an entire C# application, compile it, save it to disk and execute it (dirty, dirty thinking)..Geordie
The first paragraph is not correct: Process.Start does not look at the list of running OS processes. This documentation statement only talks about that object instance of the Process class. The Process class can be attached to a running process but it can also be in an unstarted state. In my opinion this is a design screw up. The best practice, IMO, is to never reuse a Process instance and to immediately start it after creation. Ideally, use the static Process.Start method. Then, this documentation and design flaw never come into play.Leaky
The code shown here is also unreliable because of WaitForExit(1000). But the entire waiting is not necessary to start a new process. It might be additional behavior that you want, but it's not required to start a new process.Leaky
I don't know about now, but nine years ago (ahem) this was definitely correct. :-)Forestforestage
J
18

I might be late to the party but here is my simple solution and it works like a charm with every application I have:

        try
        {
            //run the program again and close this one
            Process.Start(Application.StartupPath + "\\blabla.exe"); 
            //or you can use Application.ExecutablePath

            //close this one
            Process.GetCurrentProcess().Kill();
        }
        catch
        { }
Jedidiah answered 24/11, 2011 at 1:26 Comment(10)
Works very well on Win-7-x64 and Win-XP-x32. I see nothing about any constraints in the docs. This should be the accepted answer.Envision
@Envision The link to the docs you posted states "If the process is already running, no additional process resource is started." It's the 3rd line in the remarks section. I wish it wasn't this way, but it is.Forestforestage
@Forestforestage I guess we could argue about what "constraints" means to each of us. But the section is titled "Remarks" not "Constraints". So I can live with it. And why do you wish it wasn't this way? Did you experience any problems with that? Because I didn't. Works flawlessly for me.Envision
@Forestforestage This is nothing personal or anything but the idea of using a second app or a script just to restart my C# app is repellent to me. Win7 executes this method in Release mode flawlessly so far (I use it to restart my app when user changes language = nothing important). So I would rather tell the user to restart the app manually than to use methods I don't approve of myself. I've used scripts in the past and I totally didn't like it.Envision
@BitterBlue I agree that using a 2nd app sucks - I said so in my answer. But have you tried the single-app method outside the debugger? It didn't work on some versions of Windows when left this answer, and Release or Debug mode had nothing to do with it. If it works for you, great! But I got bitten by this problem and what I got were hundreds of angry users.Forestforestage
@Tommix - you can get the name of the current executable file. its not a big deal you can just make it as dynamic as you want. please read the comment I added in the code "or you can use Application.ExecutablePath". however, this solution is simple and straightforward. I posted it because I've tried all the posted solutions and non of them worked as expected. so use it don't use it up to you.Jedidiah
This works good for me, even when I have a mutex limitign it to one instance.Eiffel
After trying all of the above, this is the most consistent solution in all environments.Grunter
One more thing, if you are in debugging mode this will start another process and the remaining running program will not be related to the ongoing debugging, as a matter of a fact, Visual Studio will take it as the application was just closed. It will also prevent Visual Studio to compile as the Bin file will be in use. So, make sure you close the program opened after the restart.Grunter
This is the only solution working for me yet. Btw, you could use Process.Start(Application.ExecutablePath) as first statement, it does the same but you dont have to type in the exe-filename.Hooch
K
15

I had the same exact problem and I too had a requirement to prevent duplicate instances - I propose an alternative solution to the one HiredMind is proposing (which will work fine).

What I am doing is starting the new process with the processId of the old process (the one that triggers the restart) as a cmd line argument:

// Shut down the current app instance.
Application.Exit();

// Restart the app passing "/restart [processId]" as cmd line args
Process.Start(Application.ExecutablePath, "/restart" + Process.GetCurrentProcess().Id);

Then when the new app starts I first parse the cm line args and check if the restart flag is there with a processId, then wait for that process to Exit:

if (_isRestart)
{
   try
   {
      // get old process and wait UP TO 5 secs then give up!
      Process oldProcess = Process.GetProcessById(_restartProcessId);
      oldProcess.WaitForExit(5000);
   }
   catch (Exception ex)
   { 
      // the process did not exist - probably already closed!
      //TODO: --> LOG
   }
}

I am obviously not showing all the safety checks that I have in place etc.

Even if not ideal - I find this a valid alternative so that you don't have to have in place a separate app just to handle restart.

Kerf answered 7/1, 2010 at 14:13 Comment(5)
IMHO that there is a neater solution to this. I also have a requirement to have single instance and allow the user to restart the application (e.g. when it crashes). I nearly implemented your solution, however it occurred to me that it would be better to simply add a different command line argument that allows multiple instances to run.Doscher
mmm, you're reversing the logic - I like it! Only issue is that if someone figures out the cmd line argument that allows multiple instances strange stuff could happen :DKerf
Well, I was fortunate that it was a feature that users had been requesting so it was WIN-WIN. I would prefer they 'find' an /allowMultipleInstances flag than the rather strange /restart one.Doscher
Yeah if you allow for multiple instances that is a better solution for sure :)Kerf
@Kerf Nice. I think I'll change my flag to "-waitForProcessToExit" or something but otherwise that's a more elegant solution. Right now I'm grappling with a ClickOnce problem with referencing one EXE from another EXE, and this would solve that.Forestforestage
C
9

It's simple, you just need to call the Application.Restart() method, this will invoke your application to be restarted. You must also exit from the local environment with an error code:

Application.Restart();
Environment.Exit(int errorcode);
   

You can create an enumeration of error codes so that you application will exit efficeintly.
Another method is to just exit from the application and start the process using the executable path:

Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath);
Cimah answered 1/4, 2013 at 7:26 Comment(1)
Worked well for me, no need for the watchdog app in my case.Kyne
K
7

Start/Exit Method

// Get the parameters/arguments passed to program if any
string arguments = string.Empty;
string[] args = Environment.GetCommandLineArgs();
for (int i = 1; i < args.Length; i++) // args[0] is always exe path/filename
    arguments += args[i] + " ";

// Restart current application, with same arguments/parameters
Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath, arguments);

This seems to work better than Application.Restart();

Not sure how this handles if your program protects against multiple instance. My guess is you would be better off launching a second .exe which pauses and then starts your main application for you.

Kacerek answered 22/4, 2009 at 21:54 Comment(4)
That might not work if application is protected from multiple instances.Pileus
Yah, I have a feeling calling Application.Exit() only causes some message to be added to a queue somewhere that needs to be pumped, so the second bit of code here in my answer probably would indeed not work.Kacerek
Unfortunately this technique doesn't work (I wish it did! It's so much more simple than my solution). It will work inside the Visual Studio debugger but not in practice. See my answer for a kludgy solution that works outside the debugger.Forestforestage
HiredMind might be right. I ended up going with a Watchdog pattern solution.Kacerek
S
4

Try this code:

bool appNotRestarted = true;

This code must also be in the function:

if (appNotRestarted == true) {
    appNotRestarted = false;
    Application.Restart();
    Application.ExitThread();
}
Stickpin answered 27/7, 2011 at 11:28 Comment(0)
Q
4

I figured an another solution out, perhaps anyone can use it, too.

string batchContent = "/c \"@ECHO OFF & timeout /t 6 > nul & start \"\" \"$[APPPATH]$\" & exit\"";
batchContent = batchContent.Replace("$[APPPATH]$", Application.ExecutablePath);
Process.Start("cmd", batchContent);
Application.Exit();

Code is simplified so take care of Exceptions and stuff ;)

Queenqueena answered 24/6, 2016 at 10:21 Comment(0)
C
3

I fear that restarting the entire application using Process is approaching your problem in the wrong way.

An easier way is to modify the Program.cs file to restart:

    static bool restart = true; // A variable that is accessible from program
    static int restartCount = 0; // Count the number of restarts
    static int maxRestarts = 3;  // Maximum restarts before quitting the program

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        while (restart && restartCount < maxRestarts)
        {
           restart = false; // if you like.. the program can set it to true again
           restartCount++;  // mark another restart,
                            // if you want to limit the number of restarts
                            // this is useful if your program is crashing on 
                            // startup and cannot close normally as it will avoid
                            // a potential infinite loop

           try {
              Application.Run(new YourMainForm());
           }
           catch {  // Application has crashed
              restart = true;
           }
        }
    }
Criticaster answered 20/2, 2014 at 22:10 Comment(2)
It is worth mentioning that with this solution you could restart the application X times, then thereafter quit the application to avoid an infinite loop.Thousandth
Thanks @Thousandth I've added a counter to do just that, in case the program cannot exit normally.Criticaster
R
2

You are forgetting the command-line options/parameters that were passed in to your currently running instance. If you don't pass those in, you are not doing a real restart. Set the Process.StartInfo with a clone of your process' parameters, then do a start.

For example, if your process was started as myexe -f -nosplash myfile.txt, your method would only execute myexe without all those flags and parameters.

Ricoricochet answered 23/4, 2009 at 4:34 Comment(0)
T
2

You could also use Restarter.

Restarter is an application that automatically monitor and restarts crashed or hung programs and applications. It was originally developed to monitor and restart game servers, but it will do the job for any console or form based program or application

Toolis answered 9/4, 2011 at 9:21 Comment(1)
The supplied link no longer works, but I think this is the same application on CNET: download.cnet.com/Restarter/3000-2094_4-75810552.htmlTerrorist
P
2

I wanted the new application start up after the old one shuts down.

Using process.WaitForExit() to wait for your own process to shutdown makes no sense. It will always time out.

So, my approach is to use Application.Exit() then wait, but allow events to be processed, for a period of time. Then start a new application with the same arguments as the old.

static void restartApp() {
    string commandLineArgs = getCommandLineArgs();
    string exePath = Application.ExecutablePath;
    try {
        Application.Exit();
        wait_allowingEvents( 1000 );
    } catch( ArgumentException ex ) {
        throw;
    }
    Process.Start( exePath, commandLineArgs );
}

static string getCommandLineArgs() {
    Queue<string> args = new Queue<string>( Environment.GetCommandLineArgs() );
    args.Dequeue(); // args[0] is always exe path/filename
    return string.Join( " ", args.ToArray() );
}

static void wait_allowingEvents( int durationMS ) {
    DateTime start = DateTime.Now;
    do {
        Application.DoEvents();
    } while( start.Subtract( DateTime.Now ).TotalMilliseconds > durationMS );
}
Phantom answered 7/6, 2012 at 8:37 Comment(0)
L
2
public static void appReloader()
    {
        //Start a new instance of the current program
        Process.Start(Application.ExecutablePath);

        //close the current application process
        Process.GetCurrentProcess().Kill();
    }

Application.ExecutablePath returns your aplication .exe file path Please follow the order of calls. You might want to place it in a try-catch clause.

Litha answered 1/7, 2016 at 9:25 Comment(0)
B
2

The problem of using Application.Restart() is, that it starts a new process but the "old" one is still remaining. Therefor I decided to Kill the old process by using the following code snippet:

            if(Condition){
            Application.Restart();
            Process.GetCurrentProcess().Kill();
            }

And it works proper good. In my case MATLAB and a C# Application are sharing the same SQLite database. If MATLAB is using the database, the Form-App should restart (+Countdown) again, until MATLAB reset its busy bit in the database. (Just for side information)

Baal answered 15/2, 2017 at 15:50 Comment(0)
D
1

How about create a bat file, run the batch file before closing, and then close the current instance.

The batch file does this:

  1. wait in a loop to check whether the process has exited.
  2. start the process.
Damning answered 15/12, 2011 at 1:54 Comment(2)
Which is a poor man's watchdog application, which I describe a little more detailed above. The key benefit of a real watchdog application is that it will even handle if the original app dies without being able to spin something off.Kacerek
@AdamNofsinger I see now. I missed that comment. You might want to edit your post with that solution you use.Damning
S
1

Here's my 2 cents:

The sequence Start New Instance->Close Current Instance should work even for the applications that don't allow running multiple copies simultaneously as in this case the new instance may be passed a command-line argument which will indicate that there is a restart in progress so checking for other instances running will not be necessary. Waiting for the first instance to actually finish my be implemented too if it's absolutely imperative that no two intstances are running in parallel.

Sloppy answered 27/3, 2012 at 15:42 Comment(0)
B
1
Application.Restart();
Environment.Exit(0);
Bargeboard answered 11/10, 2022 at 10:6 Comment(1)
This will start restart the application and then will exit successfully. This is not the OP wants.Heroism
R
0

I had a similar problem, but mine was related to unmanageable memory leak that I couldn't find on an app that has to run 24/7. With the customer I agreed that safe time to restart the app was 03:00AM if the memory consumption was over the defined value.

I tried Application.Restart, but since it seems to use some mechanism that starts new instance while it is already running, I went for another scheme. I used the trick that file system handles persist until process that created them dies. So, from The Application, i dropped the file to the disk, and didn't Dispose() the handle. I used the file to send 'myself' executable and starting directory also (to add flexibility).

Code:

_restartInProgress = true;
string dropFilename = Path.Combine(Application.StartupPath, "restart.dat");
StreamWriter sw = new StreamWriter(new FileStream(dropFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
sw.WriteLine(Application.ExecutablePath);
sw.WriteLine(Application.StartupPath);
sw.Flush();
Process.Start(new ProcessStartInfo
{
    FileName = Path.Combine(Application.StartupPath, "VideoPhill.Restarter.exe"),
    WorkingDirectory = Application.StartupPath,
    Arguments = string.Format("\"{0}\"", dropFilename)
});
Close();

Close() at the end would initiate app shutdown, and file handle I used for StreamWriter here would be held open until process really dies. Then...

Restarter.exe comes into action. It TRIES to read the file in exclusive mode, preventing it to gain access until main app wasn't dead, then starts main app, deletes the file and exists. I guess that it can't be simpler:

static void Main(string[] args)
{
    string filename = args[0];
    DateTime start = DateTime.Now;
    bool done = false;
    while ((DateTime.Now - start).TotalSeconds < 30 && !done)
    {
        try
        {
            StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
            string[] runData = new string[2];
            runData[0] = sr.ReadLine();
            runData[1] = sr.ReadLine();
            Thread.Sleep(1000);
            Process.Start(new ProcessStartInfo { FileName = runData[0], WorkingDirectory = runData[1] });
            sr.Dispose();
            File.Delete(filename);
            done = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Thread.Sleep(1000);
    }
}
Rabato answered 9/4, 2011 at 9:11 Comment(0)
L
0

I use the following and it does exactly what you are looking for:

ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
UpdateCheckInfo info = null;
info = ad.CheckForDetailedUpdate();
if (info.IsUpdateRequired)
{
    ad.UpdateAsync(); // I like the update dialog
    MessageBox.Show("Application was upgraded and will now restart.");
    Environment.Exit(0);
}
Leeke answered 28/10, 2015 at 16:16 Comment(0)
C
0

You could enclose your code inside a function and when restart is needed you can just call the function.

Countercheck answered 13/7, 2019 at 15:1 Comment(0)
E
0

Take for instance an application that:

  1. While application is not registered; (upon start) the application should prompt the user to register the application and create a login account.

  2. Once registration is submitted and login credentials are created; the application should restart, check for registration and prompt the user to login with the inserted credentials (so the user can access to all the application features).

Problem: By building and launching the application from Visual Studio; any of the 4 alternatives bellow will fail to accomplish the tasks required.

/*
 * Note(s):
 * Take into consideration that the lines bellow don't represent a code block.
 * They are just a representation of possibilities,
 * that can be used to restart the application.
 */

Application.Restart();
Application.Exit();
Environment.Exit(int errorCode);
Process.GetCurrentProcess().Kill();

What happens is: After creating the Registration, Login and calling Application.Restart(); the application will (strangely) reopen the Registration Form and skip data in a Database (even though the resource is set to "Copy if Newer").

Solution: Batch Building the application was (for me) a proof that any of the lines above were actually working as expected. Just not when building and running the application with Visual Studio.

In first place I'd try batch building the application; run it outside Visual Studio and check if Application.Restart() actually works as expected.

Also Check further Info regarding this thread subject: How do I restart my C# WinForm Application?

Euterpe answered 2/12, 2020 at 13:30 Comment(0)
A
0

I've found a new way that's pretty convenient and has quite a few upsides.

  • There's never more than one instance running.
  • Command line args are persisted.
  • No exit events are raised from the application.
  • No process handles are broken.

I had a third party application managing my application with Process.Start and using Exit event to reload the application. Many of these solutions would break this implementation which is how I ended up on the following solution.

public static CancellationTokenSource _restartTokenSource;
/// <summary>
///  The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
    // To customize application configuration such as set high DPI settings or default font,
    // see https://aka.ms/applicationconfiguration.
    ApplicationConfiguration.Initialize();

            
    while (_restartTokenSource == null || _restartTokenSource.IsCancellationRequested)
    {
        _restartTokenSource = new System.Threading.CancellationTokenSource();
        _restartTokenSource.Token.Register(() =>
        {  
            foreach (Form form in Application.OpenForms)
                form.Close();
        });

        Application.Run(new FlashMain(args));
    }
}

Since Application.Run blocks until all forms in the application are closed I put this portion of the initialization into a loop that only executes when a CancellationTokenSource is null (the first run) or IsCancellationRequested is true (restart requested).

I register an event on the CancellationTokenSource that closes all forms in the application when .Cancel() is called, therefore unblocking Application.Run and restarting the loop.

Call Program._restartTokenSource.Cancel(); anywhere in the application to restart it.

P.S. This also works great for injecting into a BlazorWebView to restart the application from .NET Core.

Accord answered 7/1, 2023 at 6:3 Comment(0)
P
0
using System.Diagnostics;

Process p = new Process();
p.StartInfo.FileName = Application.ExecutablePath;
p.Start();

Thread.Sleep(1000);

Environment.Exit(0);
Poison answered 12/8, 2023 at 10:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.