C# 实现超大文本文件读取暂停和继续功能
当需要在读取超大文本文件时添加暂停和继续功能时,可以使用多线程和异步操作来实现。下面是一个示例代码,演示了如何在读取文件时实现暂停和继续功能:
using System;
using System.IO;
using System.Threading;
class Program
{
private static bool isPaused = false;
private static bool isStopped = false;
static void Main()
{
string filePath = 'path/to/file.txt';
int bufferSize = 4096;
// 创建一个线程来执行文件读取操作
Thread readingThread = new Thread(() =>
{
try
{
using (StreamReader sr = new StreamReader(filePath))
{
char[] buffer = new char[bufferSize];
int bytesRead;
while ((bytesRead = sr.Read(buffer, 0, bufferSize)) > 0)
{
// 检查是否需要暂停或停止
if (isPaused)
{
Console.WriteLine('已暂停');
while (isPaused) { } // 等待暂停状态解除
Console.WriteLine('继续');
}
if (isStopped)
{
Console.WriteLine('已停止');
break;
}
// 处理读取的数据
string data = new string(buffer, 0, bytesRead);
Console.WriteLine(data);
}
}
Console.WriteLine('读取完成');
}
catch (Exception ex)
{
Console.WriteLine('读取文件时发生错误: ' + ex.Message);
}
});
// 启动文件读取线程
readingThread.Start();
// 主线程循环接收用户输入,以控制暂停和继续
while (true)
{
string input = Console.ReadLine();
if (input.ToLower() == 'pause')
{
isPaused = true;
}
else if (input.ToLower() == 'resume')
{
isPaused = false;
}
else if (input.ToLower() == 'stop')
{
isStopped = true;
break;
}
}
// 等待文件读取线程结束
readingThread.Join();
Console.WriteLine('程序结束');
}
}
在上述代码中,通过创建一个读取文件的线程 readingThread,并在主线程中监听用户的输入进行控制。当用户输入'pause'时,将设置 isPaused 标志为 true,从而使读取线程进入暂停状态。当用户输入'resume'时,将设置 isPaused 标志为 false,从而解除暂停状态。当用户输入'stop'时,将设置 isStopped 标志为 true,从而停止文件读取线程。
请注意,上述示例代码只是为了演示暂停和继续的实现方式,并未处理线程同步和异常处理等方面的细节。在实际应用中,你可能需要更多的处理逻辑和错误处理机制来确保程序的稳定性和可靠性。
原文地址: https://www.cveoy.top/t/topic/puN 著作权归作者所有。请勿转载和采集!