For being thread safe do we need to assign function parameters to the local variables. I am going to explain it with an example
public static bool CheckEmailExist_1(string srEmail)
{
//Do some stuff with using srEmail
}
public static bool CheckEmailExist_2(string Email)
{
string srEmail=Email;
//Do some stuff with using srEmail
}
Are there any thread safe difference when these 2 functions evaluated. I mean for example lets say CheckEmailExist_1 got 100 concurrent call with of course different email parameters. Would that cause any problem during the function inside operations ?
c# 4.0 , asp.net 4.0
Thank you
Local variables won’t have issues with thread safety. Thread safety becomes a concern when there is shared state between multiple threads. In that function since you are passing the result By Value (which is the default for primitive types such as string, integers, decimals) thread safety is not an issue since there is no shared state. Objects on the other hand are passed By Reference and thread safety might becomes an issue.
Here is a classic example. The value of _unsafe should be 10000 since you have 100 threads incrementing the _unsafe variable 100 times but it may not be when you run the program. This is because the value may be read by one thread that performs it’s calculations and then while it’s performing it’s calculations the value of the variable would be incremented by another thread. This is called a race condition and is something to avoid. Here is a great ebook on threading that covers all the topics you need to know.
http://www.albahari.com/threading/
Here is another unsafe example using objects. This has the same problem as the previous example since there are multiple thread working on the same piece of data (in this case it’s the class variable “unsafe”)