C# .NET - When calling a random function twice i get the same value

Asked By Annie X on 11-Mar-13 09:02 AM

Hi, hope you can help.

When I call a random function twice i get the same value and i'm not sure why. Could you have a look at the code please and see if you can spot where I've gone wrong please.

All the best AnnieX

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FruitMachine : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      string strBtnTxt = "START";
      btnStart.Text = strBtnTxt;
      btnStart.ToolTip = strBtnTxt;

      if (!Page.IsPostBack) {
        try {
          lblReel1.Text = "X";
          lblReel2.Text = "X";

        }
        catch (Exception ex) {
          Response.Write(ex.ToString());
        }
      }//if (!Page.IsPostBack)
    }
   
    protected void btnStart_Click(object sender, EventArgs e)
    {
      try {
        lblReel1.Text = cRandomLetterNumberGenerator.RandomLetterNumberGenerator();

        lblReel2.Text = cRandomLetterNumberGenerator.RandomLetterNumberGenerator();

      }
      catch(Exception ex){
        Response.Write(ex.ToString());
      }
    
    }
}


class used
-------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for cRandomLetterNumberGenerator
/// </summary>
public class cRandomLetterNumberGenerator
{
    public static string RandomLetterNumberGenerator()
 {
      string result = string.Empty;
      try
      {
        //// Initialize the string array
        string[] strLetters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
        Random RandLetter = new Random(); //Choose a random letter
        result = strLetters[RandLetter.Next(0, strLetters.Length)];
      }
      catch (Exception ex) { }
      return result;
 }
}

Robbe Morris replied to Annie X on 11-Mar-13 12:32 PM
public class RandomNumber
{
  private static readonly Random Global = new Random();
  [ThreadStatic]
  private static Random _local;
  public int Next(int max)
  {
    var localBuffer = _local;
    if (localBuffer == null)
    {
    int seed;
    lock (Global)
    seed = Global.Next();
    localBuffer = new Random(seed);
    _local = localBuffer;
    }
    return localBuffer.Next(max);
  }
}

Debug.WriteLine(RandomNumber.Next(15));
Debug.WriteLine(RandomNumber.Next(15));
Debug.WriteLine(RandomNumber.Next(15));
Debug.WriteLine(RandomNumber.Next(15));
Debug.WriteLine(RandomNumber.Next(15));
Annie X replied to Robbe Morris on 12-Mar-13 03:14 PM
Hi, Thank you for the help.

All the best
AnnieX