我希望以線程安全的方式迭代集合。我覺得這是convieniant有一個方法叫一個更好的方式使用函數委託通過行動委託
/// <summary>
/// This visits all items and performs an action on them in a thread manner
/// </summary>
/// <param name="visitAction">The action to perform on the item</param>
public void VisitAllItems(Action<Item> visitAction) {
lock (listLock) {
foreach (Item item in this.ItemList) {
visitAction.Invoke(item);
}
}
}
它的一個例子是使用可
/// <summary>
/// Saves each item in the list to the database
/// </summary>
protected static void SaveListToDatabase() {
this.VisitAllItems(item => {
bool itemSavedSuccessfully = item.SaveToDB();
if(!itemSavedSuccessfully) {
//log error message
}
});
}
它的另一個例子我們使用將
/// <summary>
/// Get the number of special items in the list.
/// </summary>
protected int GetNumberOfUnsynchronisedItems() {
int numberOfSpecialItems = 0;
this.VisitAllItems((item) => {
numberOfSpecialItems += item.IsItemSpecial() ? 1 : 0;
});
return numberOfSpecialItems;
}
但我敢肯定有是編寫VisitAllItems
方法以使用Func<>
而不是Action<>
委託來返回此值的更好方法。我已經嘗試了幾件事情,但最終出現編譯錯誤。
任何人都可以看到一個整潔的方式來實現這種方法?
感謝, 麥金太爾
由於雙方svick和@jonskeet。根據我的情況,我理解你的兩個解釋,並且兩者似乎都是合適的。除非我能說服別人,否則我已經給了你點,沒有比有人需要挑戰jon更好的理由。歡呼聲 – ajmccall 2012-03-14 00:23:39
你不應該根據聲譽得分來決定,而只能根據答案本身來決定。此外,你可以(也應該)通過提升他們來「給予多於一個答案的積分」。你應該提出所有你認爲好或有用的答案。 – svick 2012-03-14 00:27:20
公平點(http://blog.stackoverflow.com/2010/01/stack-overflow-where-we-hate-fun/)。但我接受的答案仍然存在。 +1以及@JonSkeet。 – ajmccall 2012-03-14 06:12:10