• C# Mutex


    Mutex

    Mutex 类似于C# lock, 区别在于一个Mutex可以在多个进程间使用.也就是说Mutex既是computer-wide又是application-wide.

    注意: 获取和释放Mutex大概比lock要多五十倍时间.

    调用WaitOne()来获得锁, ReleaseMutex()来解除锁.关闭或者杀死Mutex会自动释放掉锁.和lock一样, Mutex只能从拥有它的线程释放掉.

    cross-process Mutex的常见用处是用来确保某个程序只有一个实例在运行.

    代码如下:

    class OneAtATimePlease
    {
    static void Main()
    {
    // Naming a Mutex makes it available computer-wide. Use a name that's
    // unique to your company and application (e.g., include your URL).
    using (var mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"))
    {
    // Wait a few seconds if contended, in case another instance
    // of the program is still in the process of shutting down.
    if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))
    {
    Console.WriteLine ("Another instance of the app is running. Bye!");
    return;
    }
    RunProgram();
    }
    }
    static void RunProgram()
    {
    Console.WriteLine ("Running. Press Enter to exit");
    Console.ReadLine();
    }
    }


    在Terminal Services下运行时, computer-wide Mutex 只有在同一个terminal server session 中的程序可见, 如果要让它在所有 Terminal Serverces sessions 可见, 则需要在它名字前面加上.


  • 相关阅读:
    C#-练习题
    C#-命名空间(十五)
    C#-枚举(十三)
    C#-多态(十二)
    C#-继承(十一)
    C#-结构体(十)
    C#-类(九)
    C#-方法(八)
    二叉树深度遍历和广度遍历
    iOS main.m解析
  • 原文地址:https://www.cnblogs.com/riasky/p/3481795.html
Copyright © 2020-2023  润新知