Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting current process C#

I have an app that has some installer inside I want to reload everything associated to the app therefor I want to restart the process. I've searched and saw the Application.Restart() and it's drawbacks and wondered what's the best way to do what I need - closing the process and restarting it. or if there's any better way to reinitialize all objects.

like image 973
user271077 Avatar asked Jul 24 '11 09:07

user271077


People also ask

How do I restart a PID process?

To restart a stopped process, you must either be the user who started the process or have root user authority. In the ps command output, find the process you want to restart and note its PID number. In the example, the PID is 1234 . Substitute the PID of your process for the 1234 .

How do I restart a process in terminal?

Type sudo systemctl restart service into Terminal, making sure to replace the service part of the command with the command name of the service, and press ↵ Enter . For example, to restart Apache on Ubuntu Linux, you would type sudo systemctl restart apache2 into Terminal.

Can a process restart itself?

No process can revive itself once killed. There can be many reasons for a process restarting right after it's killed.


1 Answers

I would start a new instance and then exit the current one:

private void Restart()
{
    Process.Start(Application.ExecutablePath);

    //some time to start the new instance.
    Thread.Sleep(2000);

    Environment.Exit(-1);//Force termination of the current process.
}

private static void Main()
{
    //wait because we maybe here becuase of the system is restarted so give it some time to clear the old instance first
    Thread.Sleep(5000);

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(...
}

Edit: However you should also consider adding some sort of mutex to allow only one instance of the application to run at time, Like:

private const string OneInstanceMutexName = @"Global\MyUniqueName";

private static void Main()
{
    Thread.Sleep(5000);
    bool firstInstance = false;
    using (System.Threading.Mutex _oneInstanceMutex = new System.Threading.Mutex(true, OneInstanceMutexName, out firstInstance))
    {
        if (firstInstance)
        {
            //....
        }
     }
}
like image 142
Jalal Said Avatar answered Sep 30 '22 13:09

Jalal Said