Force kill on process

c#

Solution

`Timer` instead of `System.Threading.Thread.Sleep` in loop

timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (2);             
timer.Enabled = true;                       
timer.Start();

void timer_Tick(object sender, EventArgs e)
    {
        System.Diagnostics.Process[] pname =   System.Diagnostics.Process.GetProcessesByName("mstsc");

        if (pname.Length != 0)
        {

        }
        else
        {
        System.Diagnostics.Process.Start(@"mstsc.exe");
        }
    }

Problem

I have this loop that runs continuously as a process to check if the `mstsc.exe` is running. ``` for (; ; ) { System.Diagnostics.Process[] pname = System.Diagnostics.Process.GetProcessesByName("mstsc"); if (pname.Length != 0) { } else { System.Diagnostics.Process.Start(@"mstsc.exe"); } System.Threading.Thread.Sleep(3000); } ``` The problem is that on logoff, reboot, or shutdown I get this. I tried to end the process on Form_Closing or with ``` Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded); ``` and I still get this... How could I force this process to kill correctly?

Original source

Related problems