gpt4 book ai didi

c# - 在 C# 中使用全局互斥锁的好的模式是什么?

转载 作者:IT王子 更新时间:2023-10-29 03:27:54 26 4
gpt4 key购买 nike

Mutex 类很容易被误解,而 Global mutexes 更是如此。

创建全局互斥锁时使用什么好的、安全的模式?

一个会起作用的

  • 无论我的机器所在的语言环境如何
  • 保证正确释放互斥量
  • 可选地,如果未获取互斥锁,则不会永远挂起
  • 处理其他进程放弃互斥量的情况

最佳答案

我想确保它在那里,因为很难做到正确:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier

static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();

// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

// Need a place to store a return value in Mutex() constructor call
bool createdNew;

// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);

// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}

// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}

关于c# - 在 C# 中使用全局互斥锁的好的模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/229565/

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