Possible Duplicate:
F# getting a list of random numbers
I’m getting random value from list each time on tick (timer) but I’m getting the same 3 times only then it changes…
the code:
let timer = new DispatcherTimer()
timer.Tick.Add <| fun _ -> X.Change()
timer.Interval <- new TimeSpan(0,0,3)
member X.Change() =
(Seq.nth
(System.Random().Next(Seq.length actions))
<| actions)()
Why? I want to get different value each time
I’m not entirely sure about your example, but the general guideline is that you should create one instance of
System.Random(or one instance per thread, if you have a multi-threaded application) and then use it multiple times.Try something like this:
The
Randomobject is mutable and keeps some state that is used to generate the sequence of random values. When you create a new instance, it initializes the state using current time, so if you create multiple instances at the same time, you’ll get the same numbers.As an aside, if you need to access random elements of
actions, then it would be better to store them as an array, because then you can just write: