创建MutexAccessRule触发System.ArgumentNullException的问题排查
单应用实例Mutex检测在System.Threading.AccessControl 9.0.0下触发ArgumentNullException的问题
问题背景
基于经典Mutex方案实现的单应用实例检测功能,此前运行稳定,近期在创建MutexAccessRule时触发System.ArgumentNullException,错误提示参数identity为null,但实际identity变量并非null。
核心实现代码:
var identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var allowEveryoneRule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); var mutex = new Mutex(true, __MUTEX_ID, out createdNew); mutex.SetAccessControl(securitySettings);
排查过程
为定位问题,尝试了多种identity创建方式均未解决异常:
- 通过当前用户身份创建:
identity = WindowsIdentity.GetCurrent().Owner; identity = WindowsIdentity.GetCurrent().Owner.AccountDomainSid; - 通过已知Well-Known SID创建:
identity = new SecurityIdentifier(WellKnownSidType.BuiltinDomainSid, null); identity = new SecurityIdentifier(WellKnownSidType.NTAuthoritySid, null); - 通过NTAccount字符串直接创建规则:
string user = Environment.UserDomainName + "\\" + Environment.UserName; var allowEveryoneRule = new MutexAccessRule(user, MutexRights.FullControl, AccessControlType.Allow); - 通过SID转换为NTAccount后创建规则:
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var acct = sid.Translate(typeof(NTAccount)) as NTAccount; var allowEveryoneRule = new MutexAccessRule(acct.ToString(), MutexRights.FullControl, AccessControlType.Allow);
根因定位
经过版本回退测试,确认问题由**System.Threading.AccessControl包从8.0.0升级至9.0.0**导致,回退到8.0.0版本后,异常完全消失,功能恢复正常。
后续计划
将向官方提交该版本兼容性bug报告。
内容的提问来源于stack exchange,提问作者Adam Calvet Bohl
相关产品推荐
相关产品推荐

