添加到列表时循环列表
我已经用 c-sharp (winforms) 构建了我的系统,但遇到了问题。在我看来 - 我的图形界面 - 我正在启动一个相当繁重的算法,它在每个循环中将结果添加到我视图中的列表中。该算法使用后台工作程序在演示者(MVP 模式)中运行 - 使视图不会冻结。正如我之前所说,算法在循环中运行,由于它太重了,所以我想在算法的结果进来时对其进行处理。
查看:
...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...
Presenter中的Backgroundworker:
...
_view.Results.Add(result);
...
综上所述,我怎样才能开始处理列表而后台工作者添加了它?当然,后台工作程序可以比列表的处理速度更快,反之亦然 - 处理可能必须等待结果到达列表,并且列表需要能够构建结果堆栈。
我意识到这个问题可能很模糊,但如果你问我问题,我相信我可以更好地定义问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用队列并让两个线程将其视为生产者和消费者。
Use a queue and have the two threads treat it as a producer and consumer.
让BackgroundWorker 在视图中调用一个方法,将项目添加到列表中并对其进行处理。
Make the BackgroundWorker call a method in the view which adds the item to the list and processes it.
使用线程安全队列来驱动生产者/消费者模式,例如 .NET 4 ConcurrentQueue:http://www.codethinked.com/post/2010/02/04/NET-40-and-System_Collections_Concurrent_ConcurrentQueue.aspx
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
您是否可以使用 ObservableCollection 并捕获 CollectionChanged 事件来捕获并处理添加到集合中的每个项目?
Is it something that you can use the
ObservableCollection
and catch theCollectionChanged
event to catch and process each item as it's added to the collection?