Share via

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 | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

Developer technologies | ASP.NET Core | Other

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,606 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.

    Was this answer helpful?

    0 comments No comments

  2. P a u l 10,766 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

    Was this answer helpful?


Your answer

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