Designing a Thread Safe Class

前端 未结 6 2148
轮回少年
轮回少年 2021-02-05 11:29

When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about

6条回答
  •  无人及你
    2021-02-05 12:10

    non generic ICollection classes provide properties for thread safety. IsSynchronized and SyncRoot. unfortunately you cannot set IsSynchronized. You can read more about them here

    In your classes you can have something simlar to IsSynchronized and Syncroot , expose public methods/properties alone and inside method body check for them. Your IsSynchronized will be a readonly property, so once your instance is initialized, you will not be able to modify it

    bool synchronized = true;
    var collection = new MyCustomCollection(synchronized);
    var results = collection.DoSomething();
    
    public class MyCustomCollection 
    {
      public readonly bool IsSynchronized;
      public MyCustomCollection(bool synchronized)
      {
       IsSynchronized = synchronized
      }
    
      public ICollection DoSomething()
      { 
        //am wondering if there is a better way to do it without using if/else
        if(IsSynchronized)
        {
         lock(SyncRoot)
         {
           MyPrivateMethodToDoSomething();
         }
        }
        else
        {
          MyPrivateMethodToDoSomething();
        }
    
      }
    }
    

    You can read more about writing thread safe collections on Jared Parson's blog

提交回复
热议问题