我正在异步读取三个文件并将它们写入一个文件。问题是它只写入了 LAST 文件的内容。这是为什么?我的代码:Main的类:
public static FileReader filereader1= new FileReader("file1.txt");
public static FileReader filereader2 = new FileReader("file2.txt");
public static FileReader filereader3 = new FileReader("file3.txt");
public static FileWriter towrite = new FileWriter(writefile.txt");
public static void readFileAsync(object obj)
{
var filereader = obj as FileReader;
readf = new ReadFile(filereader.readLine);
if (filereader!=null)
{
while (!filereader.IsFinished)
{
IAsyncResult ar = readf.BeginInvoke(new AsyncCallback(myCallback),null);
}
}
}
public static void myCallback(IAsyncResult iar)
{
AsyncResult ar = (AsyncResult)iar;
ReadFile readf = (ReadFile)ar.AsyncDelegate;
string line = readf.EndInvoke(iar);
writefile.writeLine(line);
}
static void Main(string[] args)
{
readFileAsync(filereader1);
readFileAsync(filereader2);
readFileAsync(filereader3);
Console.ReadKey();
filereader1.Dispose();
filereader2.Dispose();
filereader3.Dispose();
writefile.Dispose();
类文件阅读器:
public static StreamReader toRead { get; set; }
public string FilePath { get; set; }
public FileReader(string path)
{
FilePath = path;
toRead = new StreamReader(path);
}
public string ReadLine()
{
string line=null;
if (!toRead.EndOfStream)
{
line = toRead.ReadLine();
return line;
}
return null;
}
public bool IsFinished
{
get
{
if (toRead != null)
{
return toRead.EndOfStream;
}
return true;
}
}
public void Dispose()
{
if (toRead != null)
{
toRead.Close();
}
}
}
类文件编写器:{
public StreamWriter toWrite { get; set; }
public static object locker = new object();
public string FilePath { get; set; }
public FileWriter(string path)
{
FilePath = path;
toWrite = new StreamWriter(path);
}
public void writeLine(string line)
{
if (toWrite != null)
{
lock (locker)
{
toWrite.WriteLine(line);
}
}
}
public void Dispose()
{
if (toWrite != null)
{
toWrite.Close();
}
}
}