How to lock file

前端 未结 2 1770
清歌不尽
清歌不尽 2020-12-06 10:03

please tell me how to lock file in c#

Thanks

2条回答
  •  眼角桃花
    2020-12-06 10:58

    FileShare.None would throw a "System.IO.IOException" error if another thread is trying to access the file.

    You could use some function using try/catch to wait for the file to be released. Example here.

    Or you could use a lock statement with some "dummy" variable before accessing the write function:

        // The Dummy Lock
        public static List DummyLock = new List();
    
        static void Main(string[] args)
        {
            MultipleFileWriting();
            Console.ReadLine();
        }
    
        // Create two threads
        private static void MultipleFileWriting()
        {
            BackgroundWorker thread1 = new BackgroundWorker();
            BackgroundWorker thread2 = new BackgroundWorker();
            thread1.DoWork += Thread1_DoWork;
            thread2.DoWork += Thread2_DoWork;
            thread1.RunWorkerAsync();
            thread2.RunWorkerAsync();
        }
    
        // Thread 1 writes to file (and also to console)
        private static void Thread1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                lock (DummyLock)
                {
                    Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " -  3");
                    AddLog(1);
                }
            }
        }
    
        // Thread 2 writes to file (and also to console)
        private static void Thread2_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                lock (DummyLock)
                {
                    Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " -  4");
                    AddLog(2);
                }
            }
        }
    
        private static void AddLog(int num)
        {
            string logFile = Path.Combine(Environment.CurrentDirectory, "Log.txt");
            string timestamp = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
    
            using (FileStream fs = new FileStream(logFile, FileMode.Append,
                FileAccess.Write, FileShare.None))
            {
                using (StreamWriter sr = new StreamWriter(fs))
                {
                    sr.WriteLine(timestamp + ": " + num);
                }
            }
    
        } 
    

    You can also use the "lock" statement in the actual writing function itself (i.e. inside AddLog) instead of in the background worker's functions.

提交回复
热议问题