首页 新闻 会员 周边

C# Mutex 中变量 initiallyOwned 是干什么用的

0
悬赏园豆:5 [已解决问题] 解决于 2019-06-01 15:03

// true to give the calling thread initial ownership of the named system mutex if
// the named system mutex is created as a result of this call; otherwise, false.

不是很理解

求一个详细的例子

天不遮我的主页 天不遮我 | 初学一级 | 园豆:66
提问于:2019-05-31 23:42
< >
分享
最佳答案
0

参考园子里的博文 C#线程-线程同步

initiallyOwned: 如果initiallyOwned为true,互斥锁的初始状态就是被所实例化的线程所获取,否则实例化的线程处于未获取状态。

收获园豆:5
dudu | 高人七级 |园豆:31003 | 2019-06-01 10:12

实例化的线程获取和实例化的线程处于未获取状态。会有什么不同 这里不是很明白

天不遮我 | 园豆:66 (初学一级) | 2019-06-01 12:35

@天不遮我: 拿锁与不拿锁的区别

dudu | 园豆:31003 (高人七级) | 2019-06-01 12:59

@dudu:
static void Main(string[] args)
{
string name = "tt1";

        using (Mutex mutex = new Mutex(true, name, out bool createNew))
        {
            Console.WriteLine("exists mutex " + createNew);
            mutex.WaitOne();
            Console.WriteLine("running");

            Console.ReadLine();
            mutex.ReleaseMutex();
            Console.WriteLine();
            Console.WriteLine("ReleaseMutex");
        }
        Console.ReadLine();
    }

如果我设置initiallyOwned = true
当我运行两个程序时 第二个程序会卡在mutex.WaitOne(); 当第一个程序执行mutex.ReleaseMutex();第二个程序就抛出异常了System.Threading.AbandonedMutexException: The wait completed due to an abandoned mutex.

当我设置为false时 就不会抛出异常

请问下 线程拿锁与不拿锁是什么意思 如果拿锁表示这个资源被线程占用了 那mutex.WaitOne() 有什么用

天不遮我 | 园豆:66 (初学一级) | 2019-06-01 13:44

@天不遮我: 如果设置了 initiallyOwned = true ,在new Mutex 时就拿到了锁,不需要再 mutex.WaitOne(); ,上面的代码只要去掉 mutex.WaitOne(); 就行了

dudu | 园豆:31003 (高人七级) | 2019-06-01 14:33

@dudu: 不用mutex.WaitOne(); 第二个进程会访问到Mutex 里面的内容

天不遮我 | 园豆:66 (初学一级) | 2019-06-01 14:39

@天不遮我: 不好意思,不应该去掉 mutex.WaitOne() ,应该在 createNew 为 false 时 mutex.WaitOne()

if (!createNew)
{
    mutex.WaitOne();
}
dudu | 园豆:31003 (高人七级) | 2019-06-01 14:57
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册