zoukankan      html  css  js  c++  java
  • 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 可见, 则需要在它名字前面加上.


  • 相关阅读:
    使用SpringAOP
    Alpha 冲刺 (5/10)
    Alpha 冲刺 (4/10)
    Alpha 冲刺 (3/10)
    Alpha 冲刺 (2/10)
    Alpha 冲刺 (1/10)
    项目需求分析答辩总结
    项目UML设计(团队)
    项目选题报告答辩总结
    第七次作业--项目需求分析
  • 原文地址:https://www.cnblogs.com/riasky/p/3481795.html
Copyright © 2011-2022 走看看