2017-07-16 115 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