I have a service that I am rewriting to use threading. I understand that state from one thread should not be accessed by another, but I'm a little confused by what constitutes 'state'. Does that mean any field/property/method outside of the method scope?
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"); }
}
}