C# 写大文件通过多线程写多线程写会出BUG吗修改成多线程按照顺序写给我具体代码
以下是一个简单的多线程按照顺序写大文件的示例代码:
using System;
using System.IO;
using System.Threading;
class Program
{
static void Main(string[] args)
{
string filePath = "largefile.txt";
long fileSize = 1024 * 1024 * 1024; // 1GB
// Create or overwrite the file with random data
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
byte[] buffer = new byte[1024];
Random rand = new Random();
for (long i = 0; i < fileSize; i += buffer.Length)
{
rand.NextBytes(buffer);
fs.Write(buffer, 0, buffer.Length);
}
}
// Write the file again using multiple threads in order
int threadCount = 4;
long chunkSize = fileSize / threadCount;
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
long startOffset = i * chunkSize;
long endOffset = (i == threadCount - 1) ? fileSize : (i + 1) * chunkSize;
threads[i] = new Thread(() => WriteChunk(filePath, startOffset, endOffset));
threads[i].Start();
}
foreach (Thread thread in threads)
{
thread.Join();
}
Console.WriteLine("Done");
Console.ReadKey();
}
static void WriteChunk(string filePath, long startOffset, long endOffset)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[1024];
Random rand = new Random();
for (long i = startOffset; i < endOffset; i += buffer.Length)
{
rand.NextBytes(buffer);
lock (fs)
{
fs.Seek(i, SeekOrigin.Begin);
fs.Write(buffer, 0, buffer.Length);
}
}
}
}
}
该代码首先创建一个大小为1GB的随机数据文件,然后使用多个线程按顺序写入相同的数据。每个线程都负责写入文件的一个块,使用文件锁来确保每个线程按顺序写入它们的块。最后,所有线程都完成后,程序输出“Done”并等待用户按任意键退出。
需要注意的是,这只是一个简单的示例代码,可能需要根据实际需求进行修改和优化。例如,可以使用更大的缓冲区来提高性能,或者使用异步写入来避免阻塞线程。
原文地址: https://www.cveoy.top/t/topic/bH9L 著作权归作者所有。请勿转载和采集!