What needs thread-safe code here?
Lets say we have an object that can be accessed by multiple threads and a global singleton handing out the object's reference, also accessible by multiple threads.
class Book {
private string title;
public Book(string title) {
this.title = title;
}
public string Title { get { return title; } }
}
class BookstoreSingleton {
public BookstoreSingleton Instance { ... }
public B开发者_运维知识库ook Book { get { return this.book; } }
}
Am I correct in thinking that both, the Book.Title
and BookstoreSingleton.Book
both need thread-safe code?
Your class seems immutable and thread safe. You don't need to synchronize access to those properties as they can only be read, just make sure that you initialize your singleton only once (the Instance
property) and that you cannot assign it a value a second time.
The only thing that really needs synchronization is the Instance
function in the singleton class, and only then if you create your instance lazily. The rest should be fine, since the book is immutable.
I agree with cHao.
The classic way to do it is to include
public class BookstoreSingleton {
private static readonly BookstoreSingleton instance = new BookstoreSingleton()
public BookstoreSingleton Instance { return instance; }
public Book Book { get { return this.book; } }
}
as member of the BookstoreSingleton class. Not a lazy as we would be if Instance is the only static member, it will do the job perfectly and is perfectly thread safe as specified by the c# specs (static initializer are executed only once). The readonly ensure that this is the only time the instance member will be set.
That's for the singleton part but now where do you set the BookstoreSingleton's Book member. You probably need thread safety there except if you put it in the private BookstoreSingleton constructor only called once by the static initializer.
精彩评论