Question

I have list of database connections that only one of them is valid. my application should connect to them and try to get user information based on input userId.

               private string GetDatabaseId(string userId)
               {
                string dbId = string.Empty;
                Parallel.ForEach(dictionaryAllDatabases, (db, state) =>
                    {
                        user = GetUserFromDatabase(db.Key, userId);
                        if (user != null)
                        {
                            //we found user in database.set the db.Id and exit the loop
                            //it takes only 500 milliseconds to hit this line
                            dbId = db.Key;
                            state.Stop();
                            return;
                        }

                    }
                );
               //after about 15 seconds, we reach here
               .....
               }

it takes less than 500 milliseconds that it finds the valid database and then I call state.Stop() to exit the loop. but it takes about 15 seconds to exit the loop.

Am I doing something wrong?

thanks

P.S.I got the same result if I use Parallel.For

Était-ce utile?

La solution

You're probably waiting for the connections on the other tasks to fail.

Try setting the connection timeout to say 2 seconds.

Stop does not forcefully stop the other tasks, it just prevents new tasks from starting. Parallel.ForEach decides how to partition the work among tasks.

A better option would be to use Connection.OpenAsync with a cancellation token and use Task.WaitAny().

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top