我有大量数据,我需要每 5 秒制作一次“.txt”文件,然后在新创建的“.txt”文件中写入下一个数据,但是当我尝试使用定时器线程时,程序运行正常但是一段时间后,它将通过异常无法访问已关闭的文件。请在我的代码中帮助我,并建议我必须做什么。
public class Program
{
public static void Main(string[] args)
{
Service s = new Service();
s.init();
}
}
class Service
{
FileStream fs = null;
int filecount = 0;
long a = 1000000000000000;
// int j = 0;
public void init()
{
initialiseFile(filecount);
timer();
WriteINFile();
}
private void initialiseFile( int filecount)
{
fs = File.Create("C:\\Users\\yogesh.ghonate\\source\\repos\\ConsoleApp3\\ConsoleApp3\\NewFolder1\\Index_" + filecount + ".txt");
}
private void WriteINFile()
{
string sen = " write in file ";
for (int i = 0; i < a; i++)
{
Byte[] title = new UTF8Encoding(true).GetBytes(sen);
fs.Write(title, 0, title.Length);
}
}
public void timer()
{
System.Timers.Timer th = new System.Timers.Timer();
th.Interval = 5000;
th.Elapsed += new ElapsedEventHandler(run);
th.Start();
run(th, null);
}
public void run(object state, ElapsedEventArgs e)
{
Commitzfile();
}
private void Commitzfile()
{
//Stopwatch stopwatch = new Stopwatch();
//stopwatch.Start();
fs.Flush();
fs.Close();
// fs.Dispose();
//stopwatch.Stop();
filecount++;
initialiseFile(filecount);
}
}
弑天下
相关分类