Reputation: 151
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
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
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