I am using the C# 4.0 AsParallel() extension method and getting an UnAut开发者_StackOverflow社区horizedAccessException when accessing the file system
foreach (var item in items.AsParallel())
{
File.Open(@"c:\file.txt");
}
The reason why is that by default File.Open opens with Sharing disabled. By using AsParallel you are having multiple threads trying to open the file at the same time with sharing disabled. This fails as expected.
You'll need to either
- Not do this in parallel
- Open the file with sharing enabled
Try File.Open(@"c:\file.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
You have more than one thread trying to access the file. Using code that high level (meaning File.Open ) won't do, you need to use something that sets the Share level.
精彩评论