M
Michal
Hi,
maybe it's a simple problem for most of you, but I can't find an easy way to
quite simple problem, let me describe:
Let's have this code:
public ClassToChange()
{
... //some other methods
internal List<AnyDataClass> LockAndGetData()
{
Monitor.Enter(cs);
return data;
}
internal Unlock()
{
Monitor.Exit(cs);
}
private object cs = new object();
private List<AnyDataClass> data = new List<AnyDataClass>();
}
public class Editor
{
public Editor(ClassToChange editedObject)
{
this.editedObject = editedObject;
}
public void MyFunctionToChangeData()
{
List<AnyDataClass> data = editedObject.LockAndGetData();
... // change data
editedObject.Unlock();
}
private ClassToChange editedObject;
}
class Program
{
static void Main()
{
Editor ed = new Editor(new ClassToChange());
ed.MyFunctionToChangeData();
}
}
So my aim is to let Editor change the data of ClassToChange in a thread-safe
way. But as you can see to call all the List data =
editedObject.LockAndGetData(), then not to forget the editedObject.Unlock()
is very boring to write (and not so safe). Do you have any easy solution for
this?
Only solution I have, there might be the CS as attribute of ClassToChange
and use lock {} in Editor, but I would need an attribute to every data object
of ClassToChange, who would check if the cs is locked to make it safe. So
that's also not a good way.
Any ideas?
maybe it's a simple problem for most of you, but I can't find an easy way to
quite simple problem, let me describe:
Let's have this code:
public ClassToChange()
{
... //some other methods
internal List<AnyDataClass> LockAndGetData()
{
Monitor.Enter(cs);
return data;
}
internal Unlock()
{
Monitor.Exit(cs);
}
private object cs = new object();
private List<AnyDataClass> data = new List<AnyDataClass>();
}
public class Editor
{
public Editor(ClassToChange editedObject)
{
this.editedObject = editedObject;
}
public void MyFunctionToChangeData()
{
List<AnyDataClass> data = editedObject.LockAndGetData();
... // change data
editedObject.Unlock();
}
private ClassToChange editedObject;
}
class Program
{
static void Main()
{
Editor ed = new Editor(new ClassToChange());
ed.MyFunctionToChangeData();
}
}
So my aim is to let Editor change the data of ClassToChange in a thread-safe
way. But as you can see to call all the List data =
editedObject.LockAndGetData(), then not to forget the editedObject.Unlock()
is very boring to write (and not so safe). Do you have any easy solution for
this?
Only solution I have, there might be the CS as attribute of ClassToChange
and use lock {} in Editor, but I would need an attribute to every data object
of ClassToChange, who would check if the cs is locked to make it safe. So
that's also not a good way.
Any ideas?