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"); }
}
}
source to share
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.
source to share