makerofthings7
makerofthings7

Reputation: 61463

How should I handle thread updates to an internal Dictionary, possibly after thread.delegate exits?

I have N threads that are each saving data to a private Dictionary<string,myObject> myUploadObject variable with instance-object scope.

Once there is sufficient data in that dictionary, or after 2 minutes pass, I'll upload that collection to the server.

I've never encountered this multi-threaded situation and not sure how to approach this. Here is how I'm launching my initial code:

        PerfmonClient agent = new PerfmonClient(Machine, Start, Stop, Interval, MaxIterations);
        Thread newThread = null;
        Console.WriteLine("Creating new thread: " + agent.ToThreadName());
        ThreadStart threadDelegate = new ThreadStart(agent.TestLoop);
        newThread = new Thread(threadDelegate);
        agent.AssociatedThread = newThread;
        AgentDictionary.Add(agent.ToThreadName(), agent);
        newThread.Start();

Now I'm trying to get data out of within the agent object and send it to the server. I would normally just call another method within the instance of PerfmonClient to do so, but the threading concept is making me double check my approach.

Here are some ways I'm considering taking that collected data and sending it to the server:

Thank you for answering these questions... or pointing me in the right direction. I'm not sure if I'm re-inventing the wheel here and may need to learn something new.

Upvotes: 0

Views: 132

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160912

I would have a central uploader thread that provides a method AddPerformanceData to add performance data that the collection threads can call. This method uses a lock and stores the data internally. The uploader thread then sends that data in order using the lock for access as well.

This has the advantage that you don't need any locks on the collection threads since no-one else is accessing their data - you basically serialize the upload through the uploader thread.

Upvotes: 1

Related Questions