c# 多线程按顺序写文件 代码
以下是一个示例代码,可以实现多线程按顺序写文件:
using System;
using System.IO;
using System.Threading;
class Program
{
static object lockObject = new object();
static int currentFile = 1;
static int totalFiles = 10;
static void Main(string[] args)
{
for (int i = 1; i <= totalFiles; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(WriteToFile));
t.Start(i);
}
Console.ReadLine();
}
static void WriteToFile(object fileNumber)
{
int number = (int)fileNumber;
while (true)
{
lock (lockObject)
{
if (number == currentFile)
{
// write to file
using (StreamWriter writer = new StreamWriter($"file{number}.txt"))
{
writer.WriteLine($"This is file number {number}.");
}
Console.WriteLine($"File {number} written.");
currentFile++;
if (currentFile > totalFiles)
{
break;
}
}
}
Thread.Sleep(10);
}
}
}
这个程序会创建10个线程,每个线程负责写入一个文件。在写入文件之前,线程会先获取一个锁,以确保当前文件是下一个要写入的文件。如果当前文件不是下一个要写入的文件,线程就会释放锁并等待一段时间,然后再次尝试获取锁。如果当前文件是下一个要写入的文件,线程就会写入文件并将当前文件的编号加1。在所有文件都写入完成后,程序会退出。
原文地址: https://www.cveoy.top/t/topic/bIcO 著作权归作者所有。请勿转载和采集!