多线程写文件异常(正由另一进程使用,因此该进程无法访问该文件)的解决方法

来源:互联网 发布:115会员淘宝购买 编辑:程序博客网 时间:2024/05/20 22:03

正由另一进程使用,因此该进程无法访问该文件。
   在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

 

这是由于多线程出现互斥,一个文件没关闭,继续写入数据流而产生的异常。

经过lock(vb.net里monitor)加锁没能解决问题,后来觉得用互斥量mutex比较不错,经测试问题解决,异常通知没有了。

 

namespace filewrite
{
    public partial class Form1 : Form
    {
        Mutex mtx = new Mutex();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 30; i++)
            {
                Thread checkclientOnline = new Thread(checkOnline);
                checkclientOnline.Start();
            }

        }
        //写入日志
        public static void WriteToLog1(string Title)
        {
           

            if (Title == "") return;
            string FileName = Application.StartupPath;
            //Object thisLock = new Object();
           
            {
                FileStream fs = new FileStream(FileName + "//tiplog.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
                Byte[] bTitle = UnicodeToMBCS(Title);
                fs.Write(bTitle, 0, bTitle.Length);
                fs.Close();
            }
        }

        public static Byte[] UnicodeToMBCS(String src)
        {
            Encoding enc = Encoding.GetEncoding(936); ////Dont use codepage 52936, but 54936 or 936
            int len = src.Length;

            Byte[] tmpb = new Byte[len * 2];

            tmpb = enc.GetBytes(src);

            //string tmphead=tmpb.Length.ToString();
            //tmphead=tmphead.PadLeft(4,'0');   

            //tmpb=enc.GetBytes(tmphead+src);
            return tmpb;
        }
        void checkOnline()
        {
            while (true)
            {
                try
                {
                   
                    mtx.WaitOne();
                    //Write file here
                    WriteToLog1("hhh");
                    mtx.ReleaseMutex();
                   ;
                }catch(Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
}

原创粉丝点击