DevyDev
DevyDev

Reputation: 886

Carefully closing processes

Main goal is to close Process and not to leave any hanging connections, sub-processes behind.

There is a simple service that's running 24/7 and every minute it is checking if there is any new job to start. If it finds one, it starts its

  public Process StartProcess(string pathToExecutable, string arguments)
        {
            var processStartInfo = new ProcessStartInfo
            {
                FileName        = pathToExecutable,
                Arguments       = arguments,
                UseShellExecute = false,
                CreateNoWindow  = true
            };

            return Process.Start(processStartInfo);
        }

And when trying to close

   public bool TryCloseProcess(Process process, int waitSeconds)
        {
            try
            {
                process.CloseMainWindow();
                process.WaitForExit(waitSeconds);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

Any proper way to be sure that all resources would be released, etc ?

Upvotes: 0

Views: 182

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

You need to focus on resource clean-up and graceful exit in the process you've started.

You cannot do it remotely, so what you do in this scheduler app is sufficient to send a message to the started process to make it stop.

The started process should handle the rest. (A graceful exit)

When you stop a process, any managed (and also unmanaged) resources it had utilized will be freed whether you Dispose() them or not.

There will be no memory leak since the full working set will be freed by your OS.

What you should consider is whether there are ongoing background processing (threads started by you, which are not marked with IsBackground = true will continue running and prevent application close), Tasks that you have started, and you should implement graceful exit for any kind of external connections etc. for these.

If one of the tasks is writing to a file at that exact moment, the file will be partially written. If a thread is doing some Network IO at that moment, that will be interrupted. It will be disconnected from the remote end prematurely. You don't need to worry about memory and handle leaks but should consider graceful-stop for these kinds of processes (file IO, network IO etc.)

Your finalizers will be invoked during termination. This is a good place to handle clean-up.

Also see here for how to use a cancellation token to stop a task when it is about to be cancelled.

Hope this helps.

Upvotes: 1

Related Questions