Domanda

I want to create an auto restarter for my server. I have added a checkbox and made all required checks but I don't have any idea how to make that process restart upon crash.

Here is my code:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    string world = textBox1.Text;
    string auth = textBox2.Text;

    if (checkBox1.Checked == true)
    {
        if (textBox1.Text.Trim().Length == 0 || textBox2.Text.Trim().Length == 0)
        {
            MessageBox.Show("Please check if you selected the path for worldserver and authserver");
        }
        else
        {
            //here i need something to restart those 2 processes after crash/close
        }
    }   
}
È stato utile?

Soluzione

The simplest way to start a process is to use the Start static method of the Process class:

Process.Start("yourapp.exe");

For access to more specific options, you can set up a ProcessStartInfo object instead:

var startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "yourapp.exe";
startInfo.Arguments = "-arg1 val1";

var exeProcess = Process.Start(startInfo);
exeProcess.Start();

To check whether the process in question is still running, you can use this:

var matchingProcesses = Process.GetProcessesByName("yourapp");
var isRunning = matchingProcesses.Length > 0;

And you can put that in a method and poll every few seconds or milliseconds (depending on how fast you want to respond):

var aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler(YourMethod);
aTimer.Interval = 1000;
aTimer.Enabled = true;

These classes are found in the System.Diagnostics and System.Timers namespaces, respectively.

Altri suggerimenti

Though it's not C# (but better, it works with almost any program), you can do an auto restarter in batch (or in bash, but I won't put the code here), and it will be enough for most cases:

@echo off
:start
myprogram.exe %*
if exist myprogam.lock goto start

inside your program:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
  if(checkBox1.Checked)
  {
     using (System.IO.File.Create("myprogam.lock"));
  }
  else
  {
     System.IO.File.Delete("myprogam.lock")
  }
}

you should also create the file in your main or init code.

bonus: you can delete the file if your program exits cleanly (or on some errors), and it won't restart.

to use, just put the first code in a .bat file you put in your program folder, and use this to start the program.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top