-2

I need to have a list or collection or even datatable. I want one process to add STRING to this list. (this can be a user clicking a button) whilst a thread is constantly running in the background and processing and removing the strings in the list.

In a nutshell whenever I add items to the list\datatable or whatever, they must be processed as the process of adding them is much faster then actually processing them.

Any suggestions as to the best method?

MaltaBd
  • 1
  • 2
  • Apart from the various concurrenct collections already available, you can use an ActionBlock to do all this using a single class – Panagiotis Kanavos Oct 19 '15 at 12:14
  • 1
    Is your collection meant to be FIFO? If that is so, then I recommend using [ConcurrentQueue](https://msdn.microsoft.com/en-us/library/dd267265(v=vs.110).aspx) – Matias Cicero Oct 19 '15 at 12:14
  • So easy to find by doing basic research by for instance searching on "thread safe list wpf" – jgauffin Oct 19 '15 at 12:20
  • @jgauffin that's not what the OP asked. In fact, most of the answers to that would be inappropriate as they'd involve async/await or Invoke, none of which has anything to do with the classic producer/consumer problem – Panagiotis Kanavos Oct 19 '15 at 12:23

1 Answers1

1

This is provided out-of-the-box with the ActionBlock class. Anything you post to the block is queued and processed by the lambda you provide when you create the block:

var myBlock = new ActionBlock<string>(data=>
{ 
        Console.WriteLine(data);
});
...
myBlock.Post("some string");

ActionBlock is part of the TPL DataFlow Library, which is available as a NuGet package

Please note that .NET has numerous concurrent collections (eg ConcurrentQueue, BlockingCollection) and processing models (Tasks, PLINQ, Dataflow, Reactive). What you ask is a rough description of the "Producer/Consumer" problem. Each of the available technologies can be used to solve it, but some are easier to use than others, depending on the problem's context.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236