End Google Ads 201810 - BS.net 01 --> 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 LockAndGetData()
{
Monitor.Enter(cs);
return data;
}

internal Unlock()
{
Monitor.Exit(cs);
}

private object cs = new object();
private List data = new List();
}

public class Editor
{
public Editor(ClassToChange editedObject)
{
this.editedObject = editedObject;
}

public void MyFunctionToChangeData()
{
List 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?
Michal
modified on Tuesday, April 27, 2010 5:16 AM