How do I make code like this thread safe?
public static class Converter
{
public static string ConvertNameToNickname(string name)
{
if (name.Equals("John"))
{
return "Johnathon";
}
return name;
}
}
Or is it already thread safe since "name" is a local variable? I just want to make sure if ConvertNameToNickname was called by two different threads the name it was evaluating wasn't being stepped on by other threads.
<--edit-->
Ok some of these answers have been pretty helpful but I still haven't ferreted out the answer I was looking for so let me modify it a bit and ask the same question. How would I make this code thread safe given a mutable-type parameter? Or is it even possible? If I throw a lock{} around the entire method body (shown in the example 2) is it still possible for the instance variable "name" to be modified before we enter the lock statement block?
public static class Converter
{
public static string ConvertNameToNickname(StringBuilder name)
{
if (name.ToString().Equals("John"))
{
return "Johnathon";
}
return name;
}
}
Example 2:
private static readonly object _lockObject = new object();
public static class Converter
{
public static string ConvertNameToNickname(StringBuilder name)
{
lock(_lockObject)
{
if (name.ToString().Equals("John"))
{
return "Johnathon";
}
return name;
}
}
}