代码改变世界

.NET多线程小记(7):进程同步Mutex

2009-11-06 15:15  敏捷的水  阅读(966)  评论(0编辑  收藏  举报

互斥体是跨进程的同步,效率非常低

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace MultiThreadTest
{
    class Program
    {

        const string file=@"C:\TestMutex.txt";

        static Mutex mutex = new Mutex(false, "TestMutext");


        static void Main(string[] args)
        {
            Thread.Sleep(3000);

            Do();

            mutex.Close();

            Console.Read();
            
        }

        static void Do()
        {
            long d1 = DateTime.Now.Ticks;

            mutex.WaitOne();

            long d2=DateTime.Now.Ticks;

            Console.WriteLine("After {0}, Process {1} get mutext",
                (d2 - d1).ToString(), Process.GetCurrentProcess().Id.ToString());

            try
            {
                if (!File.Exists(file))
                {
                    using (FileStream fs = File.Create(file)) { }
                }
                for (int i = 0; i < 5; i++)
                {
                    using (FileStream fs = File.Open(file, FileMode.Append))
                    {
                        String content = "Process:" + Process.GetCurrentProcess().Id.ToString() + "i:" + i.ToString()
                            + "\r\n";
                        byte[] data = Encoding.Default.GetBytes(content);

                        fs.Write(data, 0, data.Length);
                        Thread.Sleep(300);

                    }
                }
            }            
            finally
            {
                mutex.ReleaseMutex();
            }            
        }
    }   
}

启动三个进程

clip_image002

clip_image004