lundi 26 octobre 2020

Is this static function thread safe?

Let's say I have this static function:

public static int GetRandomInt(int maxValue)
{
    Random r = new Random();
    return r.Next(maxValue);
}

I place the function in a class that has no property and it's only purpose is to get something from the parameter. Now I've been reading about the drawback of using static function in C#, but have not yet found a clear answer, is this thread safe? is the new instance of Random is cleaned everytime it finished? the function itself will be called by multiple functions across many users. another example is this :

public class People
{
    //usual class stuff

    public static double GetAverageAge() {
        SqlConnection conn = new SqlConnection()
        // proceed to get average age from database
        return averageAge;
    }
} 

Is the function GetAverageAge thread safe too, when I call SqlConnection there?




Aucun commentaire:

Enregistrer un commentaire