简体   繁体   English

Parallel.ForEach停止或休息需要太长时间

[英]Parallel.ForEach stop or break takes too long

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. 我的应用程序应该连接到它们并尝试根据输入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. 找到有效的数据库需要不到500毫秒,然后我调用state.Stop()来退出循环。 but it takes about 15 seconds to exit the loop. 但退出循环大约需要15秒。

Am I doing something wrong? 难道我做错了什么?

thanks 谢谢

PSI got the same result if I use Parallel.For 如果我使用Parallel.For,PSI得到了相同的结果

You're probably waiting for the connections on the other tasks to fail. 您可能正在等待其他任务的连接失败。

Try setting the connection timeout to say 2 seconds. 尝试将连接超时设置为 2秒。

Stop does not forcefully stop the other tasks, it just prevents new tasks from starting. Stop不会强制停止其他任务,它只是阻止新任务启动。 Parallel.ForEach decides how to partition the work among tasks. Parallel.ForEach决定如何在任务之间对工作进行分区。

A better option would be to use Connection.OpenAsync with a cancellation token and use Task.WaitAny() . 更好的选择是将Connection.OpenAsync与取消令牌一起使用并使用Task.WaitAny()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM