gpt4 book ai didi

c# - Mutex() 和 Mutex(true ,"myMutex") 线程对象有什么区别?

转载 作者:行者123 更新时间:2023-11-30 22:05:46 25 4
gpt4 key购买 nike

我有创建多个线程的代码,所有线程都尝试将信息记录在一个文件中我尝试使用互斥锁来登录文件,但是当我使用 Mutex()Mutex(true or false, "name") 对象时,我得到了不同的响应。Mutex() 给出了正确的预期结果,但 Mutex(true/false, "myname") 缺少一些日志信息。

那么它们有什么区别呢?

System.Threading.Mutex mtx = new System.Threading.Mutex(false ,"Myname" );

try
{
try
{
mtx.WaitOne();
}
catch (AbandonedMutexException)
{ }

//log into file
}

catch (Exception)
{
Console.WriteLine("EXCEPTION CAUGHT ***");
}
finally
{
mtx.ReleaseMutex();
mtx.Close();
}

最佳答案

来自 parameterless constructor 的文档.

Calling this constructor overload is the same as calling the Mutex(Boolean) constructor overload and specifying false for initial ownership of the mutex. That is, the calling thread does not own the mutex.

第二个参数只是给互斥体一个名字。因此,例如,如果另一个进程创建了一个同名的互斥量,则现有的互斥量将在这两个进程之间共享。

关于c# - Mutex() 和 Mutex(true ,"myMutex") 线程对象有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com