正由另一进程使用,因此该进程无法访问该文件

/// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="log"></param>
        private void WriteLog(string log)
        {
            //edit at 2012.10.17 改成无锁异步写如日志文件
            using (FileStream fs = new FileStream(DataLogFile, FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous))
            {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(log+"\r\n");
                IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
                    (asyncResult) =>
                    {
                        FileStream fStream = (FileStream)asyncResult.AsyncState;
                        fStream.EndWrite(asyncResult);
                    },
                    fs);
                //fs.EndWrite(writeResult);//这种方法异步起不到效果
                fs.Close();
            }
 
            //lock (lockObj)
            //{
 
            //    //using (StreamWriter sw = File.AppendText(DataLogFile))
            //    //{
 
            //    //    sw.WriteLine(log);
            //    //    sw.Flush();
            //    //    sw.Close();
            //    //}
            //}
        }class Program

{
     static  void  Main( string [] args)
     {
         ThreadPool.QueueUserWorkItem(run);
         ThreadPool.QueueUserWorkItem(run);
         Console.ReadLine();
     }
     private  static  void  run( object  state)
     {
         while  ( true )
         {
             Append();
         }
     }
     public  static  void  Append()
     {
         try
         {
             //lock (typeof(Program))
             //{
                 using  (var writer = File.AppendText( "1.txt" ))
                 {
                     writer.Write(DateTime.Now.ToString( "HHmmss" ));
                 }
                 Console.WriteLine( "Done" );
             //}
         }
         catch  (Exception ex)
         {
             Console.WriteLine(ex);
         }           
     }
}
         static  System.Threading.Semaphore _mutex =  new  System.Threading.Semaphore( 1 1 " IOHelper.Save " );
         private   static   bool  Save( string  fileName,  string  text,  bool  isAppend)
        {
             try
            {
                 if  (_mutex.WaitOne( 2000 false )) // 进程间同步。
                {
                     using  (StreamWriter writer =  new  StreamWriter(fileName, isAppend))
                    {
                        writer.Write(text);
                    }
                }
                 return   true ;
            }
             catch  (Exception err)
            {
                Log.WriteLogToTxt(err);
            }
             finally
            {
                 try
                {
                    _mutex.Release();
                }
                 catch
                {

                }
            }
             return   false ;
        }
 
 
http://www.cnblogs.com/cyq1162/archive/2013/03/29/2988035.html

你可能感兴趣的:(文件)