1

我有一个包含各种提要 URL 的文本文件。我正在使用以下代码读取集合(IEnumerable)中的所有 URL:

var URLs = File.ReadLines(Path.GetFullPath(@"Resources\FeedList.txt"));

在下一行中,我正在打印总数:

Console.WriteLine("Total Number of feeds : {0}",URLs.Count());

之后,我使用 Parellel.ForEach 构造来执行一些逻辑,对应于每个 URL。以下是我正在使用的代码:

Parallel.ForEach(URLs, (url) =>
                                       {
                                           // Some business logic
                                       });

问题是,我得到以下异常,只要我添加代码以打印 URL 的数量,即调用的代码,URL 对象上的 Count() 方法。例外 :

Total Number of feeds : 78

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.ObjectDisposedException: Cannot read from a closed TextReader.
   at System.IO.__Error.ReaderClosed()
   at System.IO.StreamReader.ReadLine()
   at System.IO.File.<InternalReadLines>d__0.MoveNext()
   at System.Collections.Concurrent.Partitioner.DynamicPartitionerForIEnumerable`1.InternalPartitionEnumerator.GrabNextChunk(Int32 requestedChunkSize)
   at System.Collections.Concurrent.Partitioner.DynamicPartitionEnumerator_Abstract`2.MoveNext()
   at System.Threading.Tasks.Parallel.<>c__DisplayClass32`2.<PartitionerForEachWorker>b__30()
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.<>c__DisplayClass7.<ExecuteSelfReplicating>b__6(Object )
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource,TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWi
   at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3
   at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Action`1 body)
   at DiscoveringGroups.Program.Main(String[] args) in C:\Users\Pawan Mishra\Documents\Visual Studio 2010\Projects\ProgrammingCollectiveIntelligence\DiscoveringGroups\Pro
Press any key to continue . . .

如果我删除/注释掉打印计数值的行,Parallel.ForEach 循环运行良好。

有谁知道这里出了什么问题?

4

1 回答 1

4

不要var在不需要时使用(或类型明显多余时)。在这种情况下,它隐藏了正在发生的事情,你会对结果感到惊讶。

File.ReadLines方法不会读取所有行并返回一个集合,它返回一个枚举器,当您从中获取项目时读取行。它返回的类型不是字符串数组,而是一个IEnumerable<string>,如果您已指定变量的类型,您会注意到:

string[] URLs = File.ReadLines(Path.GetFullPath(@"Resources\FeedList.txt"));

这会产生编译器错误,因为该方法不返回数组,所以您会看到结果不是您所期望的。

When you use the Count() method on the enumerator, it will read all the lines in the file in order to count them, so when you later on try to use the enumeration again, it has already read all lines and closed the TextReader.

Use the File.ReadAllLines method to read all lines in the file, instead of getting an enumerator:

string[] URLs = File.ReadAllLines(Path.GetFullPath(@"Resources\FeedList.txt"));

Now you can use the array multiple times.

于 2011-10-31T08:51:47.260 回答