-1

Is AddSafe method realy thread-safe or what I'm doing is wrong?

public static MyCollection myCol = new MyCollection();

class MyCollection: ObservableCollection<string>
{
    public void AddSafe(string item)
    {
        lock(this)
        {
            this.Add(item);
        }
    }
}

1 Answers1

0

How about remove/acces, it's not only about adding? But reading items should be locked also.


There's a little problem by design: You're using an ObservableCollection which is mostly used by the GUI.

I advise you not using the ObservableCollection<> in other threads than the GUI thread. Controls who are 'listening' to the events will breakdown when triggered on other threads than the gui thread. When changing items in an ObservableCollection, it should be invoked on the Dispatcher. This way your collection is threadsafe. (because of not using it cross threading)

pseudo

public class MyControl: UserControl
{

    private void MyMethodCalledFromAnOtherThread()
    {
        this.Dispatcher.Invoke(new Action(
        {
            // Change the collection...
            myCol.Add("Hi there");
        });
    }
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • Yes it's not only about adding, I was just asking in generaly. I'm reading data form socket in separate thread so I can't do this in GUI thread – Vasilii Pupkin Dec 04 '16 at 08:54
  • You shouldnt write in the observablecollection from the socket thread. Either use `dispather.invoke` to synchronise the socker thread and the gui thread. Or even better. Use a queue to store received messages queued by the socket thread and use a DispatcherTimer to handle the queue. This way the socket thread doesnt push the gui thread. – Jeroen van Langen Dec 04 '16 at 09:07