Ben Galler
Ben Galler

Reputation: 965

Loop list while adding to it

I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...

Backgroundworker in presenter:

...
_view.Results.Add(result);
...

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.

Upvotes: 2

Views: 350

Answers (4)

dthorpe
dthorpe

Reputation: 36092

Use a threadsafe queue to drive your producer/consumer pattern, such as the .NET 4 ConcurrentQueue: http://www.codethinked.com/post/2010/02/04/NET-40-and-System_Collections_Concurrent_ConcurrentQueue.aspx

Upvotes: 2

CodingGorilla
CodingGorilla

Reputation: 19862

Is it something that you can use the ObservableCollection and catch the CollectionChanged event to catch and process each item as it's added to the collection?

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61635

Use a queue and have the two threads treat it as a producer and consumer.

Upvotes: 5

SLaks
SLaks

Reputation: 887877

Make the BackgroundWorker call a method in the view which adds the item to the list and processes it.

Upvotes: 2

Related Questions