2011-10-31 98 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」關鍵字。 –

相關問題