.NET多线程小记(7):进程同步Mutex
2009-11-06 15:15 敏捷的水 阅读(970) 评论(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();
            }            
        }
    }   
}
启动三个进程
扫码关注公众号,了解更多管理,见识,育儿等内容
作者: 王德水
出处:http://www.cnblogs.com/cnblogsfans
版权:本文版权归作者所有,转载需经作者同意。
出处:http://www.cnblogs.com/cnblogsfans
版权:本文版权归作者所有,转载需经作者同意。
                
            
        
浙公网安备 33010602011771号