-1

I have a static class called Monitor that includes a method LogToMonitor.

public static void LogToMonitor(MonitorDevice device, MonitorCategory category, MonitorType type, string msg)

It creates a MonitorEntry type and updates a property which does a property change to the UI and adds to an ObservableCollection.

 public ObservableCollection<MonitorEntry> MonitorEntries { get; }

I now have another thread that needs to LogToMonitor. This is going to cause issues having multiple calling threads. I'm thinking I should have a Producer Consumer approach.

What type of collection should I use?

Should the Queue be a separate class which processes the calls and updates the UI?

Can I have multiple threads still call LogToMonitor method which puts them in the Queue?

  • What do you mean by "type" of queue? There are a couple `Queue` classes in .NET (generic and non-generic), but they all do the same thing (more or less). It sounds like you want something with additional functionality though, is that right? – Broots Waymb Jan 07 '19 at 14:14
  • 1
    At a minimum you only need to lock your LogToMonitor function when a producer calls it. Then, when you update your gui in the context of another thread, you do the usual ``InvokeRequired`` and ``Invoke`` stuff. If your drawing takes longer than you want your threads to spend on it, your queue would not be of much help. (Unless your producers produce at a low enough and maybe bursty rate). – BitTickler Jan 07 '19 at 14:16
  • My bad use of the word type, sorry. I'll want to store my MonitorEntries in it. Don't think I need addition functionality. >>your producers produce at a low enough yup, could be an issue, thanks –  Jan 07 '19 at 14:37

2 Answers2

2

BlockingCollection<T> is what you are looking for probably. It's an implementation of the Producer-Consumer pattern. https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/blockingcollection-overview

Rahul
  • 76,197
  • 13
  • 71
  • 125
  • First try, It was easier than it seemed to implement, but had to sniff though a bunch of examples to figure it out. –  Jan 08 '19 at 03:06
0

ObservableCollection is not thread-safe so you can run into exceptions. Check the post of Robert Fraser, he has posted the code for a thread safe ObservableCollection. Use this instead of the standard implementation and should not have problems with multiple threads. How to make ObservableCollection thread-safe?

user1519979
  • 1,854
  • 15
  • 26