我想用任务并行库读取二进制文件。但是我得到了这个错误
"The process cannot access the file 'D:\Binary.bin' because it is
being used by another process."
我的代码段位于:
internal class Program
{
private static void Main()
{
new ReaderWriterBinaryFile().ReadWriteFile();
}
}
public class ReaderWriterBinaryFile
{
public void ReadWriteFile()
{
// WriteBinaryFile();
Task.Factory.StartNew(() =>
{
var fs1 = new FileStream(@"D:\Binary.bin", FileMode.Open);
var br = new BinaryReader(fs1);
ReadBinaryFile(fs1, br, 1);
});
Task.Factory.StartNew(() =>
{
var fs1 = new FileStream(@"D:\Binary.bin", FileMode.Open);
var br = new BinaryReader(fs1);
ReadBinaryFile(fs1, br, 2);
});
Console.ReadKey();
}
private void WriteBinaryFile()
{
var fs = new FileStream(@"D:\Binary.bin", FileMode.Create);
var bw = new BinaryWriter(fs);
WriteBinaryFile(fs, bw);
}
private void ReadBinaryFile(FileStream fs, BinaryReader br, int taskNo)
{
var readBytes = br.ReadBytes(4000000);
for (int i = 0; i < 1000000; i += 4)
{
var intValue = BitConverter.ToSingle(readBytes, i);
Console.WriteLine(taskNo+" ---- "+intValue);
}
fs.Close();
br.Close();
}
private void WriteBinaryFile(FileStream fs, BinaryWriter bw)
{
for (int i = 22; i < 100000000; i++)
{
var age = Convert.ToSingle(i);
bw.Write(age);
}
fs.Close();
bw.Close();
Console.WriteLine("-------write end....");
}`