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 可见, 则需要在它名字前面加上.


  • 相关阅读:
    git使用
    javascript关于事件与闭包
    Ajax和跨域
    通过触发器进行的操作
    30分钟学会jquery插件
    那些年用过的jquery插件
    网页设计常用网页技巧
    XML操作
    效果A:浏览器跳转以及判断来路客户信息
    数据库
  • 原文地址:https://www.cnblogs.com/riasky/p/3481795.html
Copyright © 2011-2022 走看看