【发布时间】:2015-06-25 15:26:08
【问题描述】:
这个例子是一个名为“WriteLines”的方法,它接受一个字符串数组并将它们添加到异步文件写入器。它有效,但我很好奇是否有一种有趣的方式来支持 -any- 字符串集合,而不是依赖程序员转换为数组。
我想出了类似的东西:
public void AddLines(IEnumerable<string> lines)
{
// grab the queue
lock (_queue)
{
// loop through the collection and enqueue each line
for (int i = 0, count = lines.Count(); i < count; i++)
{
_queue.Enqueue(lines.ElementAt(i));
}
}
// notify the thread it has work to do.
_hasNewItems.Set();
}
这似乎可行,但我不知道它有任何性能影响,或任何逻辑影响(订单会发生什么?我认为这将允许无序集合工作,例如HashSet)。
有没有更被接受的方法来实现这一点?
【问题讨论】:
-
您可以发送任何是
IEnumerable<string>(即List<string>)的内容。 IEnumerable 不能保证顺序,所以如果这很重要,您应该考虑 IEnumerable 是否适合您的需求 -
永远不要在
IEnumerable<>上使用超过一个 LINQ 方法或多次枚举它,除非您对它的生成方式有强有力的保证。有些IEnumerable<>会在您每次查看它们时重新构建...例如,如果您将File.ReadLines()作为参数传递,则该文件将为lines.Count()重新读取一次,并且为每个ElementAt重新读取一次。跨度>
标签: c# performance collections