I have a list of ports that I scan sequentially to connect to the database. Usually the default port works, but there are connections that use a non-standard port (which I do not have visibility). There are about 20-30 of them, and it will take a lot of time to pass through them sequentially.
Below I made an attempt to parallelize the serial algorithm when connecting to ports.
nonStdPorts = {...}; // list of all non-standard ports (max: 30); ConnectionState state = ConnectionState.FAIL; ConcurrentStack<ConnectInfo> results = new ConCurrentStack<ConnetInfo>(); // Assume single instance. Add an outer for-loop if multiple instances are present. Parallel.For(0, nonStdPorts.Length, (i, loopState) => { ConnectInfo connector = new ConnectInfo(serverName, databaseName, port); connector.State = TryConnect(serverName, databaseName, nonStdPorts[i], ref dbConnection); results.Push(connector); if (connector.State == ConnectionState.SUCCESSFUL) { loopState.Stop(); } } );
The helper class, ConnectInfo, is defined below:
class ConnectInfo { ConnectInfo(serverName, databaseName, port) {} State { get; set; } DbConnection { get; set; } }
and ConnectionState is for enumeration only: FAIL or SUCCESSFUL. (I'm only interested in getting the status of SUCCESSFUL).
My thinking is that if he manages to get a connection to 1 port, he will first get information (server, database, port and connection).
Am I doing it right (especially when exiting the Parallel.For loop)?
source share