以下代碼片段在循環中生成隨機數時演示了一個常見的陷阱:
<code class="language-csharp">// Inefficient random number generation public static int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); }</code>
>在緊密的循環中反複調用此功能,例如:
><code class="language-csharp">byte[] mac = new byte[6]; for (int x = 0; x < 6; x++) { mac[x] = (byte)RandomNumber(0, 255); }</code>
>通常會在mac
>Random
解決方案:一個,共享的實例
正確的方法涉及創建一個單個實例並在整個循環中重複使用。 還應考慮用於多線程應用程序的線程安全。 這是一個改進的版本:
>通過使用Random
>實例,我們確保創建一個
<code class="language-csharp">// Efficient and thread-safe random number generation private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { return random.Next(min, max); } }</code>>語句可以在多線程場景中保護種族條件,確保只有一個線程一次訪問
>方法。 這保持了生成數字的完整性和隨機性。
以上是為什麼在緊密的循環中重複呼叫`random.next()`?的詳細內容。更多資訊請關注PHP中文網其他相關文章!