Conor
Conor

Reputation: 573

Setting Timer to alternate between two intervals for random number generation

I want to display two different randomly generated numbers in two different text boxes. The numbers in the text boxes change every second. I am invoking System.Random to create the random numbers:

    private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

The issue I am running into is that System.Random generates numbers based upon the system time, so the text boxes generate two identical random numbers every second of the tick. I have tried to approach this problem by staggering generation of the numbers by 20 ms. I have done this by creating two different timers (one for each text box) that alternate between 980 and 1020 ms intervals:

    private void timer1_Tick(object sender, EventArgs e)
    {
        int xgpscoord;

        timer1.Interval = 980;
        xgpscoord = RandomNumber(10000, 90000);
        textBoxGPSx.Text = xgpscoord.ToString();
        timer1.Interval = 1020;


    }

    private void timer2_Tick(object sender, EventArgs e)
    {

        int ygpscoord;

        timer2.Interval = 1020;
        ygpscoord = RandomNumber(10000, 90000);
        textBoxGPSy.Text = ygpscoord.ToString();
        timer2.Interval = 980;


    }

However, this does not synchronize the timers. I want them to tick every 1000 ms simultaneously. I think (correct me if I am wrong) that I am setting the intervals in the wrong places and only one of the two intervals that I set in each timer is actually being counted.

If there is a better way to generate random numbers within c# not based upon system time, that would solve my problem as well.

Upvotes: 1

Views: 2538

Answers (1)

Casperah
Casperah

Reputation: 4554

You should make your Random static eg:

private static Random random = new Random();
private int RandomNumber(int min, int max)
{
    return random.Next(min, max);
}

That way you will only create one Random-instance and you will keep creating new random numbers when calling RandomNumber.

Regarding the intervals, they should be set initially (E.g. class constructor)

public Form1()
{
    InitializeComponent();
    timer1.Interval = 1000;
}

private void timer1_Tick(object sender, EventArgs e)
{
    textBoxGPSx.Text = RandomNumber(10000, 90000).ToString();
    textBoxGPSy.Text = RandomNumber(10000, 90000).ToString();    
}

Hope this will help you in your quest.

Upvotes: 1

Related Questions