Reputation: 3670
Is calling the instance method RenderHelp
in the example below thread safe? It calls static methods of the Helper
class but does not use any static variables of that class.
If 2 or more different instances of Helper
(each running on different threads) call RenderHelp
, can there ever be a problem?
public class Helper
{
public string ID { get; set; }
// other fields
static int[] Multiply(int[] a, int[] b)
{
if (a.Length == b.Length) return a.Zip(b, (a1, b2) => a1 * b2).ToArray();
else return null;
}
static int[] Add(int[] a, int[] b)
{
if (a.Length == b.Length) return a.Zip(b, (a1, b2) => a1 + b2).ToArray();
else return null;
}
public int[] RenderHelp(string help, int[]a, int[] b)
{
if (help == "Add".ToLower()) { return Add(a,b); }
else if (help == "Multiply".ToLower()) { return Multiply(a,b); }
else return null;
}
}
Links to relevant MSDN or other docs will be very much appreciated. Thank you.
*Also why doesn't stackoverflow properly format get
, as in above?
Upvotes: 2
Views: 1082
Reputation: 34489
Yes this is thread-safe. Threading issues generally occur around sharing resources, which you're not doing here. This is following the Microsoft threading suggestions:
Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility for threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests.
If you were to use a static variable somewhere in these functions, then no it wouldn't be thread safe unless you started putting locking or other thread safe ways of handling that variable.
Upvotes: 4