using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.IO; using System.Windows.Forms; using System.Threading; namespace ClientApp { class AsyncWriteFileDemo { static void Main(string[] args) { Console.WriteLine("****Fun with async writer****"); Console.WriteLine("Main Thread started,ThreadID={0}", Thread.CurrentThread.GetHashCode()); FileStream fs = new FileStream("logfile.txt", FileMode.Append, FileAccess.Write, FileShare.None, 4096, true); string msg = "this is a test "; byte[] buffer = Encoding.ASCII.GetBytes(msg); fs.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(WriteDone), fs); Console.ReadLine(); } private static void WriteDone(IAsyncResult ar) { Console.WriteLine("AsyncCallback method on ThreadID={0}", Thread.CurrentThread.GetHashCode()); Stream s = (Stream)ar.AsyncState; s.EndWrite(ar); s.Close(); } } } 必须使用13行中的构造函数来创建一个FileStream