Do I need to block read-only services when using streams?

I have a service that I am rewriting to use streams. I understand that state from one thread should not be available to another, but I am a little confused as to what constitutes "state". Does this mean any field / property / method outside of the scope of the method?

Specifically, my service looks something like this:

public class MyService
{
      private IRepository<MyClass> repository;
      private ILogger log;
      ...
      public void MyMethod()
      {
        ...
        var t = new Thread(MyMethodAsync);
        t.Start(someState);
      }

      //Is this OK???
      public void MyMethodAsync(object state)
      {
          var someState = (MyState)state;
          log.Log("Starting");
          var someData = repository.GetSomeData(someState.Property);
          //process data
          log.Log("Done");            
      }

      //Or should I be doing this:
      public void MyMethodAsync2(object state)
      {
          var someState = (MyState)state;
          lock(log){
             log.Log("Starting");  }

          lock(repository){         
             var someData = repository.GetSomeData(someState.Property);}

          //process data   
          lock(log){
             log.Log("Done"); }            
      }
}

      

+1


source to share


3 answers


Er ... no, you don't need to block read-only resources. The purpose of blocking them is that if you need to check the value of a resource before writing it, then another resource cannot change the value between your read and your write. i.e:.

SyncLock MyQueue
  If MyQueue.Length = 0 Then
    PauseFlag.Reset
  End If
End SyncLock

      



If we were to check the length of our queue before we set the flag to suspend the process queue thread and then another resource had to add an item to the queue, then the thread of the process thread would be in a pause state, whereas an item could be added in between checking the length queue and setting the pause flag ...

If all resources are read-only queue-only (not what I might think of one useful read-only queue application) then there is no need to block it.

+1


source


"State" is all the data contained in this class and the real issue with concurrency is write access, so your intuition is correct.



+2


source


Even worse, read-only locking of structures is a good way to create deadlocks.

0


source







All Articles