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

正由另一进程使用,因此该进程无法访问该文件。
   在 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());
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值