2017-07-16 126 views
-3

我在我的应用程序和每个线程上运行多个线程,我需要从帐户中随机获得一个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; 
} 
+0

您正在从随机化字典中选取最后一个“可用”值。也许在数千人中只有几个“可用”? – dlatikay

+1

我认为你也错过了随机!=独特的观点。你最好打赌是保留一个使用过的物品清单,并忽略它是否已经使用 –

+0

99%是可用的,isAvalible基本上是检查last_used是否在一个多小时前,他们是。 –

回答

1

这是你的问题

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

    var rand = new Random(); 

当你新的随机(快速),它会具有相同的密钥。
新随机()只有一次并使用它。

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

走这条线出来的功能:

var rand = new Random(); 

那将是更好的使随机静态的实例。 阅读关于Random类here