Gogu CelMare Gogu CelMare - 1 month ago 22
C# Question

C# windows (WinForms) child application locks sockets

I have two windows C# WinForms applications that behave the same way related to this issue. The behavior exhibits if the applications are ran in this order:
Main application starts up and part of its normal working process opens some sockets; mixture of tcp udp and multicast.
At some time pressing a button it starts another application using C# process related libraries. The second app starts ok and all is ok.

It is known and acceptable that if I start a second instance of my main app the second instance won't be able to use the sockets the first one owns.
The issue that I have is that if I shutdown the first app and restart, it won't be able to acquire the sockets anymore... until the child app is also shutdown.
Note that the second app doesn't use ANY sockets whatsoever, but somehow windows keeps the sockets locked until the second app shuts down.

I HAVE THIS QUESTION RELATED TO PROGRAMMING IN C# WIN FORMS WHICH IS ON THE TOPIC NOW WITH CAPITAL LETTERS FOR PEOPLE WHO CAN NOT DISTINGUISH ON/OFF TOPIC:

how do I solve this so that I don't need to shutdown the second app for the first one to be able to acquire its sockets (WHICH -i know - ARE FREE).

Answer

This is normal handle inheritance behavior. Unfortunately the .Net Process.Start is passing true as bInheritHandles to CreateProcess (NB. an open request to allow control of this behavior exists: Make Process.Start have a option to change handle inheritance). As a work around, use the native CreateProcess instead, see When System.Diagnostics.Process creates a process, it inherits inheritable handles from the parent process.