Cesar Augusto
Cesar Augusto

Reputation: 151

Generate a number random with interval time c#

I have a matrix int with 10 numbers, and I want to generate numbers randomly every 3 seconds. For example when run program random show number 2, wait 3 seconds show 5, wait 3 seconds show 10.... but I don't know how to add interval to generate

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random rnd = new Random();
rnd.Next(1, numbers.Length);

Upvotes: 0

Views: 4307

Answers (2)

Joe B
Joe B

Reputation: 788

use the Timer so you won't lock the thread

      void Main()
      {
    int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    Random rnd = new Random();

    System.Timers.Timer t = new System.Timers.Timer(1000);
    t.Elapsed += (s,e)=>{
        Console.WriteLine(rnd.Next(1, numbers.Length));
    };
    t.Start();
    Console.ReadLine();
     }

Upvotes: 2

steliosbl
steliosbl

Reputation: 8921

The simplest way is to use Thread.Sleep to achieve the delay:

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random rnd = new Random();
while (true)
{
    rnd.Next(1, numbers.Length);
    Thread.Sleep(3000) // 3000ms = 3 seconds
}

Be advised however that this locks the thread completely until the interval has passed. This shouldn't be a problem in a simple single-threaded program, but if you're dealing with something more complex or any sort of UI, you should look into using a timer instead.

Upvotes: 0

Related Questions