JLChen
2020-04-17 525d4d5c18ad5f8a7976f1fd20cef7f1d7e82831
Crabtree/SmartHome/IO/FileUtils.cs
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
namespace Shared.IO
{
@@ -243,6 +244,12 @@
      }
      /// <summary>
        /// 增加 读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
        /// 用于解决多线程环境写入文件问题
        /// </summary>
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim ();
       /// <summary>
      /// Writes the file by bytes.
      /// </summary>
      /// <returns><c>true</c>, if file by bytes was writed, <c>false</c> otherwise.</returns>
@@ -257,10 +264,13 @@
         System.IO.FileStream fs = null;
         try {
                //设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
                LogWriteLock.EnterWriteLock ();
            fs = new FileStream (System.IO.Path.Combine (RootPath, fileName), FileMode.Create, FileAccess.Write);
            fs.Write (bytes, 0, bytes.Length);
            fs.Flush ();
            Utlis.WriteLine ("SaveFile:" + fileName);
            //Utlis.WriteLine ("SaveFile:" + fileName + " : " + bytes.Length.ToString());
                //if (!UserConfig.Instance.LocalFiles.Contains (fileName)) {
                //    UserConfig.Instance.LocalFiles.Add (fileName);
                //}
@@ -270,6 +280,8 @@
            return false;
         } finally {
            try {
                    //退出写入模式,释放资源占用
                    LogWriteLock.ExitWriteLock ();
               if (fs != null) {
                  fs.Close ();
               }