我正在尝试从数据库(oracle)读取blob并将文件保存到系统中。由于blob大小可能很大,我附加字节。这里的扫描字符串是ConcurrentDictionary类型。
ConcurrentQueue<Exception> exceptions = new ConcurrentQueue<Exception>();
Parallel.ForEach(scannedLettersDictionary.Where(y => y.Value.ScannedLetterContent != null).Select(x => x), file =>
{
try
{
using (FileStream stream = new FileStream(ScannedLettersDirectory + file.Value.LetterId + ".tiff", FileMode.Create, FileAccess.Write))
{
byte[] bytes = new byte[65536];
int numBytesToRead = (int)file.Value.ScannedLetterContent.Length;
int bytesRead = 1;
using (BinaryWriter writer = new BinaryWriter(stream))
{
while (numBytesToRead > 0 && bytesRead > 0)
{
bytesRead = file.Value.ScannedLetterContent.Read(bytes, 0, Math.Min(numBytesToRead, bytes.Length));
writer.Write(bytes);
numBytesToRead -= bytesRead;
}
writer.Flush();
writer.Dispose();
}
}
}
catch (AggregateException ag) { exceptions.Enqueue(ag); }
catch (Exception e) { exceptions.Enqueue(e); }
});
if (exceptions.Count > 0)
{
foreach (var exp in exceptions)
{
LogError(exp, 66, exp.Message, _letterId);
}
}
问题出在这条线上。它给了我访问冲突例外。
bytesRead = file.Value.ScannedLetterContent.Read(bytes, 0, Math.Min(numBytesToRead, bytes.Length));
如何在Parallel.ForEach中使byte []线程安全。我不想把锁对象放在它之外,因为它不会为我提供任何用途,并且相当于for循环(性能明智)。
感谢任何帮助。