2013-05-15 29 views
2

我使用這個代碼在5月C#MonoTouch的應用程序中保存的日誌:共享衝突爲我的日誌管理

public static void writeExeption(string message){ 
     string path= StorageClass .LogsPath ; 
     string filepath= Path.Combine (path ,"Log.txt"); 
     if(!File.Exists (filepath)){ 
      using (StreamWriter sw = File.CreateText(filepath)) 
      { 
       sw.WriteLine ("--------------------------------------------------------------------------" + 
           "--------------------"); 
       sw.WriteLine("blahblah..."); 
       sw.WriteLine ("--------------------------------------------------------------------------" + 
           "--------------------"); 
      } 
     } 
     using (StreamWriter w = File.AppendText(filepath)) 
     { 
      Log(message , w); 
     } 
    } 

    public static void Log(string logMessage, TextWriter w) 
    { 
     w.Write("\r\nLog Entry : "); 
     w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), 
        DateTime.Now.ToLongDateString()); 
     w.WriteLine(" :"); 
     w.WriteLine(" :{0}", logMessage); 
     w.WriteLine ("--------------------------------------------------------------------------" + 
         "--------------------"); 
    } 

但在應用我得到這個錯誤:

Sharing violation on path 'File Path' 
+1

** 1 **。在哪一行?你到目前爲止嘗試過什麼? ** 2。**可能重複http://stackoverflow.com/questions/11541244/sharing-violation-on-path-error-c-sharp以及http://stackoverflow.com/questions/14313303/file -sharing-violation-occurrence-occur-creation-of-file –

+0

line「w.WriteLine(」:{0}「,logMessage);」 。我試過http://stackoverflow.com/questions/3817477/simultaneous-read-write-a-file-in-c-sharp和http://social.msdn.microsoft.com/Forums/en-US/vblanguage/線程/ 52f4f8fb-a434-4660-9806-3a30e3bbffb2但不適合我。我也看到你現在發送的鏈接。 –

+0

如果您想在.net中執行日誌記錄,則應該使用一個輕量級框架(如log4net或Nlog),它們將爲您處理所有文件訪問和線程同步。不要試圖自己寫。 – Peter

回答

1

嘗試添加以包含將數據附加到lock語句中的StreamWriter。 首先,添加一個目標是指:

static object _locker = new object(); 

然後,通過鎖定最後using語句修改writeExeption方法:

lock (_locker) 
{ 
    using (StreamWriter w = File.AppendText(filepath)) 
    { 
     Log(message, w); 
    } 
} 

如果這仍然不起作用,這意味着一些其他的應用程序使用您的文件。如果它工作,這意味着你正在登錄多個線程。

1

好像您正在兩個或更多位置訪問一個文件(可能位於不同的線程中)。

使用這些方法來讀/寫在多線程應用程序文件,以避免這樣的錯誤:

/// <summary> 
    /// Writes the file exclusively. No one could do anything with file while it writing 
    /// </summary> 
    /// <param name="path">Path.</param> 
    /// <param name="data">Data.</param> 
    public static void WaitFileAndWrite(string path, byte[] data) 
    { 
     while (true) { 
      Stream fileStream = null; 

      try { 
       // FileShare.None is important: exclusive access during writing 
       fileStream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None); 
       fileStream.Write(data, 0, data.Length); 

       break; 
      } catch (IOException ex) { 
       Console.WriteLine (ex); 
       Thread.Sleep(10); 
      } finally { 
       if (fileStream != null) { 
        fileStream.Close(); 
       } 
      } 
     } 
    } 

    /// <summary> 
    /// Waits the file and read. 
    /// </summary> 
    /// <returns>The file and read.</returns> 
    /// <param name="fileName">File name.</param> 
    public static byte [] WaitFileAndRead(string fileName) 
    { 
     byte[] result = null; 

     if (File.Exists(fileName)) { 
      while (true) { 
       Stream fileStream = null; 

       try { 
        fileStream = File.OpenRead(fileName); 
        var length = fileStream.Length; 
        result = new byte[length]; 
        fileStream.Read(result, 0, Convert.ToInt32(length)); 
        break; 
       } catch (IOException ex) { 
        Console.WriteLine (ex); 
        Thread.Sleep(10); 
       } finally { 
        if (fileStream != null) { 
         fileStream.Close(); 
        } 
       } 
      } 
     } 

     return result; 
    } 
} 

然而,你應該是準確的。如果有人打開文件進行讀/寫操作並且不關閉它,這些方法將嘗試無限打開。

+0

對於日誌記錄任務,您應該使用專用框架或您自己的框架,它應該同時處理多個記錄文本的請求。例如,具有**鎖定**的單身人士對象。 –

+0

感謝您的回覆。什麼是你睡覺的'線索'? –

+0

線程,誰調用讀/寫方法。它可能不是'UI'線程。 –