这是我的代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace CopyFile
{
class Program
{
static void Main()
{
long length = 0;
byte[] buffer;
string source_path, dest_path;
source_path = Console.ReadLine();
dest_path = Console.ReadLine();
FileInfo fi = new FileInfo(source_path);
length = (int)fi.Length;
// Create disk file
using (FileStream fs = File.Create(dest_path))
{
fs.Close();
}
// Create unnamed MMF
var mmf1 = MemoryMappedFile.CreateFromFile(source_path, FileMode.OpenOrCreate, null, length);
// Create reader to MMF
var reader = mmf1.CreateViewAccessor(0, length, MemoryMappedFileAccess.Read);
// Create unnamed MMF
var mmf2 = MemoryMappedFile.CreateFromFile(dest_path, FileMode.Create, null, length);
// Create writer to MMF
var writer = mmf2.CreateViewAccessor(0, length, MemoryMappedFileAccess.Write);
int read_block = int.Parse(Math.Min(length, 512 * 1024).ToString());//4k
int end_read_block = int.Parse(length.ToString()) % read_block;
int[] offset_array = new int[int.Parse((length - read_block).ToString()) / read_block];
for (int offset = 0,i=0; i < int.Parse((length - read_block).ToString()) / read_block; i++,offset += read_block)
{
offset_array[i] = offset;
}
/*
Parallel.ForEach<int>(offset_array, offset =>
{
// Read from MMF
buffer = new byte[read_block];
reader.ReadArray<byte>(offset, buffer, 0, read_block);
// Write to MMF
writer.WriteArray<byte>(offset, buffer, 0, read_block);
});
*/
foreach (int offset in offset_array)
{
// Read from MMF
buffer = new byte[read_block];
reader.ReadArray<byte>(offset, buffer, 0, read_block);
// Write to MMF
writer.WriteArray<byte>(offset, buffer, 0, read_block);
}
buffer = new byte[end_read_block];
reader.ReadArray<byte>(length - end_read_block, buffer, 0, end_read_block);
// Write to MMF
writer.WriteArray<byte>(length - end_read_block, buffer, 0, end_read_block);
}
}
}
我尝试复制一个文件并将其粘贴到它正在工作的另一个位置
但是当我尝试使用 Parallel.foreach 或 Parallel.for 复制一个文件时,复制的文件与源文件不同
(我评论了 Parallel.foreach 部分)
我不明白为什么
谢谢