/// <summary> /// new Random().Next(1, 100); 多線程同時執行結果很高几率相同, /// 是用的當前時間爲seed,時間相同結果相同 /// /// 解決隨機數重複問題 /// 同時模擬遠程請求的隨機延時 /// </summary> public class RandomHelper { /// <summary> /// 隨機獲取數字並等待1~2s /// </summary> /// <returns></returns> public int GetRandomNumberDelay(int min, int max) { Thread.Sleep(this.GetRandomNumber(500, 1000));//隨機休息一下 return this.GetRandomNumber(min, max); } /// <summary> /// 獲取隨機數,解決重複問題 /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public int GetRandomNumber(int min, int max) { Guid guid = Guid.NewGuid();//每次都是全新的ID string sGuid = guid.ToString(); int seed = DateTime.Now.Millisecond; for (int i = 0; i < sGuid.Length; i++) { switch (sGuid[i]) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': seed = seed + 1; break; case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': seed = seed + 2; break; case 'o': case 'p': case 'q': case 'r': case 's': case 't': seed = seed + 3; break; case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': seed = seed + 3; break; default: seed = seed + 4; break; } } Random random = new Random(seed); return random.Next(min, max); } }