What is a best approach to make a function or set of statements thread safe in C#?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends on what you’re trying to accomplish.
If you want to make sure that in any given time only one thread would run a specific code use
lockorMonitor:On the other hand you want multiple threads to run the same code but do not want them to cause race conditions by changing the same point in memory don’t write to static/shared objects which can be reached by multiple at the same time.
BTW – If you want to create a static object that would be shared only within a single thread use the
ThreadStaticattribute (http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx).