说我有这样的方法(从之前的被盗用乔恩斯基特SO回答):垃圾收集在产量的方法
public static IEnumerable<TSource> DuplicatesBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
// Yield it if the key hasn't actually been added - i.e. it
// was already in the set
if (!seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
在这个方法中我有一个用于保存已键一个HashSet看到。如果我在这种情况下使用这种方法。
List<string> strings = new List<string> { "1", "1", "2", "3" };
List<string> somewhatUniques = strings.DuplicatesBy(s => s).Take(2);
这只会列举字符串列表中的前2个项目。但垃圾收集如何收集seenKeys哈希集。由于yield只是暂停执行方法,如果方法很昂贵,我怎么才能确保正确处理事情?
我不能相信框架将允许hashset坐在我的appdomain关闭。不是我的迭代器会长时间坐下,这是一个提出问题的人为的例子。 – 2009-01-30 15:26:41