开发者

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

开发者 https://www.devze.com 2023-02-05 04:37 出处:网络
I have N threads that are each saving data to a private Dictionary<string,myObject> myUploadObject variable with instance-object scope.

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 m开发者_如何转开发ethod 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:

  • Create a new ThreadDelegate for the agent.upload method, load it and run it (Main thread, or spawned thread)

  • Change the internal object Dictionary<string,myObject> myUploadObject to public and static, and use a threadDelegate/Main thread to do the upload.

  • ?? Not sure what happens if the initial agent.TestLoop exits, or errors out? Do I loose all the data within the agent object? How do I access internal data it when thread.IsActive == false?

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消