0

I have a multithreaded application. The thread manager contains a list of objects of dbNodeList

class dbNodeList
{
    public string nodepath;
    public string nodename;
    public string nodevalue;
    //etc...
}

In the ThreadManager the nodepath and nodename are constants that are pre populated. In the working thread the nodevalue is pulled out of the xml message it is processing.

When the threadmanager launches a new thread it needs to give the thread a true copy of this list so when the nodevalue is filled in it is unique to that thread.

So when launching a thread I can't just say

NewThread.nodeList = ThreadManager.nodeList; as I think that is just setting a reference to the TheadManager's list. If thread_1 sets the nodevalue and then thread_2 sets it to another value, won't it be incorrect in thead_1 now?

Thanks, Rut

rut
  • 73
  • 5

2 Answers2

0

You will need to manually implement a copy function that will create a new object and copy the values over.

class dbNodeList
{
    public string nodepath;
    public string nodename;
    public string nodevalue;
    //etc...

    public dbNodeList Copy()
    {
        var copy = new dbNodeList();
        copy.nodepath = this.nodepath;
        copy.nodename = this.nodename;
        copy.nodevalue = this.nodevalue;
        //etc...

        return copy;
    }
}

//used like
NewThread.nodeList = ThreadManager.nodeList.Copy();

Any object that is a mutable reference type will need extra work done to it to make it a deep copy instead of a shallow copy, see the linked question for a explanation of the differences.

Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
0

A class is a reference type, so yes, your new thread would just be getting a reference to the existing class. Cloning is what you want to do if manually populating the class is not practical. The simplest method I've found to do that is using serialization. There is a great post here: Deep cloning objects

Community
  • 1
  • 1
DVK
  • 2,726
  • 1
  • 17
  • 20