If user click one button, it should show a random number on the button (not in messagebox). How to do that enter image description here
Asked
Active
Viewed 53 times
1 Answers
2
Try this: (Credit to this answer for providing the RandomNumber
implementation)
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock (syncLock) // synchronize
{
return random.Next(min, max);
}
}
private void button2_Click(object sender, EventArgs e)
{
button2.Text = RandomNumber(5, 10).ToString();
}
-
-
2Don't use random numbers like that. Please [read this](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Rob May 20 '16 at 01:15
-
2@MinhBui The `lock` is actually unrelated, and is a side-effect of making it static. The issue is you create a new `Random` object every time you invoke the method. Since the seed is based on the current time, multiple clicks very quickly will create `Random` objects with the same seed, so they yield the same 'random' numbers. `Random` should be a member of the class, and instantiated just once. `lock` is only required if you are using multiple threads *and* declare the random object as static – Rob May 20 '16 at 01:54
-
1
-
You uhh, don't want to instantiate a new `Random` each time the button is clicked? How fast you gonna be clicking that button Rob? Also, just how many different threads is that there button Click event going to be raised on? – xofz May 20 '16 at 04:26
-
@SamPearson How fast they are clicking is irrelevant. Better to write *correct* code, rather than code that usually works, but sometimes inexplicably does *not* work. As for threading, that's completely unrelated. When linking the answer, I was intending to educate, rather than replace the answer. An equally valid solution would be to have the `Random` object as a member, assuming the application is not threaded. – Rob May 26 '16 at 02:25