Multi-threaded question - adding an item to a static list

Ok, newbie multithreaded question:

I have a Singleton class. The class has a static list and essentially works as follows:

class MyClass {
    private static MyClass _instance;
    private static List<string> _list;
    private static bool IsRecording;

    public static void StartRecording() {
        _list = new List<string>();
        IsRecording = true;
    }

    public static IEnumerable<string> StopRecording() {
        IsRecording = false;
        return new List<string>(_list).AsReadOnly();
    }

    public MyClass GetInstance(){

    }

    public void DoSomething(){
        if(IsRecording) _list.Add("Something");
    }
}

In principle, the user can call StartRecording () to initialize the list, and then all calls to the instance method can add material to the list. However, multiple threads may contain an instance for MyClass, so multiple threads may add entries to the list.

However, creating and reading a list is a single operation, so the usual read-write problem in multi-threaded situations does not apply. The only problem I saw was the insertion order, which is strange, but it is not a problem.

, - ? , , ( _list.Add( (somedata))), , , to DateTime.Now.

: , : DoSomething ( , , -, ).

lock(_list){
    _list.Add(something);
}

and

lock(_list){
    return new List<string>(_list).AsReadOnly();
 }

?

+5
4

_list. _list, _list, - :

private static object _listLock = new object();

, :

  • DoSomething(), , , .

  • , , StartRecording(), StopRecording() DoSomething().

StopRecording() _list = null null DoSomething().

, , .

+3

, .

...

, , , , . , , , , MyClass GetInstance(), DoSomething() .

, StartRecording(). , , , , , .

, , :

static object _sync = new object();
lock(_sync){
    _list.Add(new object(somedata));
}

, , .

static object _sync = new object();
object data = new object(somedata);
lock(_sync){
    _list.Add(data);
}

, DoSomething() , , . MyClass DoSomething() , , . , MyClass GetInstance(). :

class MyClass {
    private static MyClass _instance;
    private static List<string> _list;
    private static bool IsRecording;
    public static void StartRecording()
    {
        _list = new List<string>();
        IsRecording = true;
    }
    public static IEnumerable<string> StopRecording()
    {
        IsRecording = false;
        return new List<string>(_list).AsReadOnly();
    }
    private static MyClass GetInstance() // make this private, not public
    {   return _instance;    }
    public static void DoSomething()
    {
        // use inst internally to the function to get access to instance variables
        MyClass inst = GetInstance();
    }
}

, MyClass

MyClass.GetInstance().DoSomething();

MyClass.DoSomething();
+3

.NET . MSDN: " , undefined , ". MSDN, .

, , , , - StopRecording, - DoSomething. , , , " , ".

: !

+2

, , , , . _list.Add . , , . .

+1

All Articles