3 つのファイルを非同期で読み取り、それらを 1 つのファイルに書き込んでいます。問題は、LAST ファイルの内容のみを書き込むことです。何故ですか?私のコード:メインのクラス:
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();
クラス FileReader:
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();
}
}
}
クラスFileWriter:{
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();
}
}
}