English 中文(简体)
通过改变收集方法翻新和翻新
原标题:Threading and iterating through changing collections

In C# (console app) I want to hold a collection of objects. All objects are of same type. I want to iterate through the collection calling a method on each object. And then repeat the process continuously. However during iteration objects can be added or removed from the list. (The objects themselves will not be destroyed .. just removed from the list). Not sure what would happen with a foreach loop .. or other similar method. This has to have been done 1000 times before .. can you recommend a solid approach?

问题回答

There is also copy based approach. The algorithm is like that:

  1. take the lock on shared collection
  2. copy all items from shared collection to some local collection
  3. release lock on shared collection
  4. Iterate over items in local collection

这种做法的优点是,你花了很小一段时间的共同收款(假设共同收款相对较少)。

如果你想要在每个收集项目上采用的方法需要相当长的时间才能完成或能够阻挡,那么在共享锁下进行循环的做法可能会导致阻挡希望增加/从共享收集中删除物品的其他线索。

然而,如果你想要在每一个物体上使用这种方法相对较快,那么在共同锁下进行循环可能更可取。

这是多读时的同化典型例子。

只有采取坚实做法和更好的做法,才能把从清单中提取和补充/替代物品结合起来。

你们应当允许在休息和开始循环时添加/选择!

比如:

    ENTER SYNC_BLOCK
      WAIT FOR SYNC_BLOCK to be available

      LOOP for items/ call method on them.

     LEAVE SYNC_BLOCK


     ENTER SYNC_BLOCK
      WAIT FOR SYNC_BLOCK to be available

     Add/Delete items

 LEAVE SYNC_BLOCK

我在阅读这一例子时想到的是,你可以使用http://github.com/neoeinstein/c5” rel=“nofollow noretinger”题目=“C5 Generic Collection Library”>C5TreeSet/。 这确实要求有办法订购你的物品,但以<代码”为优势。 树木的收集方法是,它们提供<代码>Snapshot方法(C5.IPersistentSorted>),使你能够在无需充分重复的情况下,对收集情况进行轻重分析。

e.g:

using(var copy = mySet.Snapshot()) {
  foreach(var item in copy) {
    item.DoSomething();
  }
}

using(var copy = mySet.Snapshot()) {
  copy.Apply(i => i.DoSomething());
}

必须指出,应当处理该表,或者如果随后对基文收集的改动,你将受到轻微的绩效处罚。

这一例子来自以下网站:http://github.com/neoeinstein/c5/raw/doc/C520book.pdf#page=167“rel=“nofollow noreferer”的题目=“C5 Book——9.11 - 用于列举树木微速的模式”,C5 Book





相关问题
Silverlight, Updating the UI during processing

I have a simple silverlight multifile upload application, and i want to provide the user with some feedback, right now its only in a test phase and i dont have the webservice. Somehow i cant get the ...

Is reading from an XmlDocument object thread safe?

I was wondering if i could safely read from an XmlDocument object using SelectNodes() and SelectSingleNode() from multiple threads with no problems. MSDN says that they are not guaranteed to be ...

Terminating a thread gracefully not using TerminateThread()

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function. At the moment I am using ...

热门标签