How to handle multithread on singleton pattern ?

ahmed salah 3,216 Reputation points
2021-10-16T22:36:38.973+00:00

I work on web api with asp.net core 3.1 I use singleton pattern on my web app

so my question is

on singleton pattern objects are the same for every object and every request so

i need to protect single objects that shared with asp.net core threads

How to handle multithread on singleton pattern that a single object shared with all ASP.NET Core threads ?

Developer technologies ASP.NET ASP.NET Core
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2021-10-16T23:50:00.49+00:00

    Do you mean how would you handle initialising the singleton instance? There are a few methods to do this, for example double-check locking or using Lazy<> - Jon Skeet's written an article about them here:
    https://csharpindepth.com/Articles/Singleton

    As for state inside the singleton itself you should consider using Interlocked where possible if you're writing shared primitive values:
    https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked?view=net-5.0

    Consider using thread-safe collections:
    https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

    And in other instances where state is mutated by one or more threads consider implementing locks where appropriate.
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement


  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-10-17T11:10:48.173+00:00

    i need to protect single objects that shared with asp .net core threads

    In general I see use of a Singleton good for global access to application setting, passed that (and I don't know exactly what you have object-wise) it would be prudent to be more specific with pseudocode explaining code flow.

    Although this code (done with C#9) is thread safe I would not use it, this was done for another question here that needed a singleton for a different purpose.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.