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


  • 相关阅读:
    有些文件不需要配置,只需要放到resources下面
    RAFT算法
    HBase,region以及HFile概念
    GitHub搭建个人网站续
    sublime text 2 安装emmet插件
    前端收录
    Zepto
    将复杂form表单序列化serialize-object.js
    PHP 清除HTML代码、空格、回车换行符的函数
    Yii2 选择布局的方式
  • 原文地址:https://www.cnblogs.com/riasky/p/3481795.html
Copyright © 2011-2022 走看看