I have a list of ports that I go through sequentially in order to connect to a database. Normally, there's a default port that works, but there are connections that use a non-standard port (which I don't have any visibility). There are about 20-30 of them, and going through them sequentially would take a long time.
Below, I made my first attempt in parallelizing the sequential algorithm in connecting to the 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 the ConnectionState being an enum holding only: FAIL or SUCCESSFUL. (I'm only interested in getting the SUCCESSFUL state).
My thinking is that if it's successful to get a connection to 1 port, it would bail out with the information (server, database, which port and the connection) on first chance.
Am I doing this correctly (especially getting out of the Parallel.For loop)?
For a parallel solution, ref dbConnection
looks very conspicuous.
You probably don't need the ref
and a Database connection can usually not be shared among threads.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.