-1

I'm working in some Winforms code right now, and I have come across lines like this several times:

...
System.Diagnostics.Process.Start(someFileName);
...

...which just kicks off some process on the client machine, and completely forgets about it. Process.Start(someFileName) returns a Process type object, which implements IDisposable, but the code is not doing anything with the object, because the whole idea was to just trigger the process and forget about it.

In this case, should the Process object still be disposed, if we're not keeping it in memory at all? Something like:

using (System.Diagnostics.Process.Start(someFileName) { }

or

var process = System.Diagnostics.Process.Start(someFileName);
process.Dispose();
Seth
  • 342
  • 1
  • 4
  • 14

1 Answers1

0

Process objects holds unmanaged resource(s) (HProcess handle)

https://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/Process.cs,f8b2e604d6f1fe04

public class Process : Component {
    //
    // FIELDS
    //

    bool haveProcessId;
    int processId;
    bool haveProcessHandle;
    SafeProcessHandle m_processHandle; // <- This should be disposed
    bool isRemoteMachine;
    string machineName;
    ProcessInfo processInfo;
    Int32 m_processAccess;
...

And thus should be disposed. Using local variable (var process = ...) looks overshooting in the context, that's why I suggest

System.Diagnostics.Process.Start(someFileName).Close();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215