[Solved] C# Process is Terminated due to StackOverFlowException


You have a recursive call without stop condition. ( killWinword calls killWinword, which calls killWinword … )

So it’s an infinite recursion. Each new call will take up more space on the stack. This will sooner or later end up in Stackoverflow.

It seems you want to do a check every second. You can:

  • Use a Timer that ticks every second.
  • Use a Task and async/await ( See Example )
  • Use a plain old Thread to execute the check in a loop, so your main Thread won’t get blocked.

(No specific order. I’d personally go for async/await but the other solutions are also valid for this simple and short program).

Caveat of Timer would be that you’d have to check if the last invocation is still running. Advantage of Task is you can easily make use of the Threadpool.

Example:

    // Run-Flag to gracefully exit loop.
    private static volatile bool _keepRunning = true;
    private static ManualResetEvent _exitRequest = new ManualResetEvent(false);
    static void Main(string[] args)
    {
        Console.WriteLine("Starting... {0} ", DateTime.Now);
        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass._keepRunning = false;
        };            

        Task.Run(() => KillWinword); // Start Task on ThreadPool
        //You don't want to use Console.Read(); So ... wait for Ctrl-C?
        _exitRequest.WaitOne();
    }

    private static async Task KillWinword()
    {
        try
        {
            // Loop instead of recursion
            while(_keepRunning)
            {
                // Do your checks here
                DoKillWinword();

                // Don't delay if exit is requested.
                if(_keepRunning) await Task.Delay(1000);
            }
        }
        finally 
        {
        _exitRequest.Set();
        }
    }

    private static void DoKillWinword()
    {
        // TIPP: You should add some Exception handling in here!

        var procs = Process.GetProcesses();

        foreach (var proc in procs)
        {
            if (proc.ProcessName == "WINWORD")
            {
                TimeSpan runtime;
                runtime = DateTime.Now - proc.StartTime;

                if (DateTime.Now > proc.StartTime.AddSeconds(20))
                {
                    proc.Kill();
                }
            }
        }
    }

Mind that this will not exactly start the check every second. It will start a new check 1 second after the previous one is done.

solved C# Process is Terminated due to StackOverFlowException