2011-10-31 96 views
1

我有一个包含各种提要URL的文本文件。我读的所有URL的使用下面的代码集合(IEnumerable的)中:Parallel.ForEach并无法从关闭的TextReader中读取异常

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

下一行,我打印总数:

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

而且我在使用中并行之后。 ForEach构造,执行一些逻辑,对应于每个URL。以下是代码,我使用:

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

的问题是,我得到以下情况例外,只要我的代码添加到打印的URL,即它调用的代码中,张数()方法在URLs对象上。例外:

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循环运行良好。

有没有人有任何想法是什么错在这里?

+0

“某些业务逻辑”中发生了什么? –

回答

4

不需要使用var(或者当类型显然是多余的时候)。在这种情况下,它会隐藏正在发生的事情,并且您会对结果感到惊讶。

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

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

这给出了一个编译器错误,因为该方法不返回数组,所以你会看到结果不是你所期望的。

当您在枚举器上使用Count()方法时,它将读取文件中的所有行以对它们进行计数,因此当您以后尝试再次使用枚举时,它已经读取了所有行并关闭了TextReader

使用File.ReadAllLines方法来读取文件中的所有行,而不是让一个枚举:

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

现在你可以多次使用数组。

+0

谢谢。学习本课,仅在必要时使用“var”关键字。 –

相关问题