从词典获取随机项目?不是随机的

时间:2017-07-16 19:24:50

标签: c# dictionary random

我在我的应用程序上运行多个线程,在每个线程中我需要从帐户中获取一个随机的Dictionary项。现在我知道当然有一段时间你会从一本小字典中得到同一个项目,但这本字典有超过一千个项目而且我仍然得到非独特的结果?

我的意思是什么?我的意思是它会给出随机结果但通常会重复

示例:

Picked the random username "aidan913"
Picked the random username "aidan913"
Picked the random username "abbiexox9"
Picked the random username "phelan193"
Picked the random username "pbeters92"

所以它有时会重复两次,但实际上并没有给出一个完全独特的项目。当然必须有一种方法来获得至少9/10次的独特项目?

public KeyValuePair<int, BotInformation> GetAccount()
{
    var account = new KeyValuePair<int, BotInformation>();

    var rand = new Random();
    var randomlyOrdered = _accounts.OrderBy(i => rand.Next());

    lock (locker)
    {
        foreach (KeyValuePair<int, BotInformation> entry in randomlyOrdered)
        {
            if (!entry.Value.Usable())
                continue;

            account = entry;
        }
    }

    if (!CoreUtilities.IsDefault(account)) // if it found one, update it?
    {
        using (var databaseConnection = Program.GetServer().GetDatabaseManager().GetConnection())
        {
            databaseConnection.SetQuery("UPDATE `accounts` SET `last_used` = '" + 
                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE `username` = '" + account.Key + "' LIMIT 1");
        }

        account.Value.LastUsed = DateTime.Now;
    }

    return account;
}

2 个答案:

答案 0 :(得分:1)

这是你的问题

public KeyValuePair<int, BotInformation> GetAccount()
{
    var account = new KeyValuePair<int, BotInformation>();

    var rand = new Random();

当你快速使用新的Random()时,它会有相同的键 新的Random()仅一次并使用它。

private var rand = new Random();
public KeyValuePair<int, BotInformation> GetAccount()
{
    var account = new KeyValuePair<int, BotInformation>();

答案 1 :(得分:0)

从功能中取出这一行:

var rand = new Random();

最好使Random静态的实例。 阅读随机课here

相关问题