While it's a fairly straightforward process to apply The Singleton Pattern, a crucial aspect that may be overlooked in whether or not it's thread safe. In this video, Reynald shows how to enhance the code to make it thread safe using the lock keyword and then goes a step further by refactoring to make the code even more concise and leaving the .Net framework to take on more responsibility. An exercise solution file is provided to compare the final results.
- [Voiceover] So we have our Singleton…but it's currently not thread-safe.…If an app is using our code in a multi-threaded environment,…two threads can hit this if statement here…on line 14 at the same time,…and we still end up having multiple instances created.…So to avoid this, what we can do is lock our code.…And we do this by adding a private read-only…object variable such as…private static readonly.…
And it'll be of type object.…And we'll call it _lock.…And then what we want to do…is wrap our if condition in the lock.…We use the keyword lock to actually lock it.…Use _lock.…Open parentheses, and that second parentheses…needs to be closed after the return statement.…
Okay, now if we Save, Build,…and right-click to run our test again,…everything still works.…And this is a popular approach.…But we can do even better.…What we can do is…let's go ahead and comment out…this line here on 11 with lock.…And what we'll do is create a read-only…statement over here on line 13,…private static readonly.…
And we're going to create a new instance of policy…
In this course, developer and technologist Reynald Adolphe explains the purpose and effective use of eight design patterns, including six Gang of Four design patterns and two .NET patterns. Gang of Four patterns fall under three categories: structural, creational, and behavioral. Reynald helps you learn about select patterns from each category. He describes each pattern and demonstrates how programmers can leverage them in real-world applications.
- Factory Method
- Abstract Factory
- Singleton pattern
- Decorator pattern
- Iterator pattern
- Observer pattern
- Repository pattern
- Unit of Work pattern
Skill Level Intermediate
2. Factory Method
3. Abstract Factory
4. Singleton Pattern
5. Decorator Pattern
6. Iterator Pattern
7. Observer Pattern
8. Repository Pattern
9. Unit of Work Pattern
Convert to Unit of Work3m 53s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.