Reading/writing of reference typed field by multiple threads WITHOUT lock
Context: highly threaded server-side application with many reads, occasional writes.
Let us consider the following simple code:
[Serializable]
public class BusinessObject
{
// ... lot's of stuff, all READ ONLY!!!
}
public class BusinessObjectHost
{
private BusinessObject bo;
public BusinessObject BO
{
get { return this.bo; }
set { this.bo = value; }
}
}
The intended use is as follows: The BusinessObject is immutable. If I occasionally want to change it, I just need to replace BusinessObjectHost.bo field with a new instance.
Q1: What happens if I do not apply any lock in BusinessObjectHost.BO property and there is a thread conflict between read and write on BusinessObjectHost.bo field? Will the thread throw exceptions? If yes, which one?
Q2: If thread crash causes exception, would the following code work?
public class BusinessObjectHost
{
private BusinessObject bo;
public BusinessObject BO
{
get
{
int i = 5; // Max 开发者_如何学编程5 tries
while (i-- > 0)
{
try { return this.bo; }
catch (WhateverThreadConflictException) {}
}
throw new MyException();
}
set
{
int i = 5; // Max 5 tries
while (i-- > 0)
{
try { this.bo = value; return; }
catch (WhateverThreadConflictException) {}
}
throw new MyException();
}
}
}
Q3: If the above solution is not good, what would you recommend?
Your BusinessObjectHost only holds a reference. References are atomic, so you will not get an exception with the simple code in snippet1.
Using it might be acceptable, depending on what you want to happen. When two or more threads now read the BO property they might get references to different instances. But you cannot prevent that from the BO property code anyway.
Q2, Q3: The code in snippet2 does not solve anything.
I believe .NET offers a class for this exact purpose.
ReaderWriterLock Class: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx
精彩评论