【C#】 Mutex简单示例

【C#】 Mutex简单示例Mutex简单示例:namespaceMutexTest{classProgram{//用于Mutex的TeststaticvoidMain(string[]args){System.Security.Cryptography.MD5md5=newSystem.Securi…

大家好,又见面了,我是你们的朋友全栈君。

Mutex简单示例:

namespace MutexTest
{
    class Program
    {
        //用于Mutex的Test
        static void Main(string[] args)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string dir = System.Environment.CurrentDirectory;
            dir = dir.Replace("/", "");
            dir = dir.Replace("\\", "");
            byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(dir));
            string md5Text = System.Text.Encoding.Default.GetString(result);
            bool runOne;
            System.Console.WriteLine("目录层级的Muxtex测试,请点开多个此程序控制台:");
            //增加using防止Muxtex在程序运行时被垃圾回收
            using (System.Threading.Mutex run = new System.Threading.Mutex(true, md5Text, out runOne))
            {
                if (!runOne)
                {
                    System.Console.WriteLine("同一目录已经运行了一个程序实例,无法重复运行");
                    System.Console.ReadLine();
                    return;  //增加return语句,防止用户回车后继续运行程序;
                }

                try
                {
                    while (true)
                    {
                        //程序执行主体代码
                        System.Console.Write(".");
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                finally
                {
                    //释放当前Mutex一次
                    run.ReleaseMutex();
                }
            }


        }
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/153223.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号