Why Static method sometimes returns same result for separate call?

三世轮回 提交于 2019-11-27 19:27:30

问题


In my c# code I have a static method. Here is the code sample:

public class RandomKey
{
    public static string GetKey()
    {
        Random rng = new Random();
        char[] chars = new char[8];
        for (int i = 0; i < chars.Length; i++)
        {
            int v = rng.Next(10 + 26 + 26);
            char c;
            if (v < 10)
            {
                c = (char)('0' + v);
            }
            else if (v < 36)
            {
                c = (char)('a' - 10 + v);
            }
            else
            {
                c = (char)('A' - 36 + v);
            }
            chars[i] = c;
        }

        string key = new string(chars);
        key += DateTime.Now.Ticks.ToString();
        return key;
    }
}

I am calling this function from another Class's method.

Class SomeClass
{
    Void SomeMethod()
    {
        for(int i=0; i<100; i++)
        {
            System.Diagnostics.Debug.WriteLine(i + "===>" + RandomKey.GetKey());
        }
    }
}

But now the problem is sometimes I am getting the same output from the static method though the function was called separately. Is there any wrong with my code?


回答1:


The reason is that you are initializing the Random object inside the method.
When you call the method in close time proximity (like inside a loop), the Random object is initialized with the same seed. (see Matthew Watson's comment to find out why.)
To prevent that you should declare and initialize the Random object as a static field, like this:

public class RandomKey
{
    static Random rng = new Random();

    public static string GetKey() 
    {
    // do your stuff...
    }
}



回答2:


You keep reinitializing the Random value. Move that out to a static field. Also you can format numbers in hex using ToString with a formatter.

Also, DateTime.Now is a bad idea. See this answer for a better way to allocate unique, timestamp values.



来源:https://stackoverflow.com/questions/30724132/why-static-method-sometimes-returns-same-result-for-separate-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!