C#-MemoryMappedFile.CreateOrOpen引发句柄无效
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-MemoryMappedFile.CreateOrOpen引发句柄无效,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2288字,纯文字阅读大概需要4分钟。
内容图文
![C#-MemoryMappedFile.CreateOrOpen引发句柄无效](/upload/InfoBanner/zyjiaocheng/656/5471424a457a4c0191fd0a26d48bfa5e.jpg)
我有创建内存映射文件的代码,如下所示:
using (Mutex mutex = new Mutex(false, CoordinatorMutexName))
{
mutex.WaitOne();
var security = new MemoryMappedFileSecurity();
security.SetAccessRule(
new AccessRule<MemoryMappedFileRights>(
new SecurityIdentifier(WellKnownSidType.WorldSid, null), // everyone
MemoryMappedFileRights.FullControl,
AccessControlType.Allow));
MemoryMappedFile coordinator = MemoryMappedFile.CreateOrOpen(
CoordinatorMMFName,
16 * 1024 * 1024 + 4,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileOptions.DelayAllocatePages,
security,
HandleInheritability.None);
...
...
}
在某些情况下(如下所述),CreateOrOpen调用将引发以下异常:
System.IO.IOException: The handle is invalid.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpenCore(SafeFileHandle fileHandle, String mapName, HandleInheritability inheritability, MemoryMappedFileSecurity memoryMappedFileSecurity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, Int64 capacity)
at System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
它只会在运行自动化测试时抛出此异常,而我不能在调试器内部或外部重现此异常.我尝试仅将上述代码提取到独立测试中,但无法重现该问题.但是有太多代码无法在此处发布所有内容. MemoryMappedFile在线程持续时间内保持不变(假定已创建),然后将其处置.
这是测试失败的条件:测试旨在从多个线程执行此代码.它们在NUnit中,在CruiseControl.NET下运行,其服务在64位Windows 2008 Server上的域帐户(而不是本地计算机帐户)下运行.登录到同一台计算机上时,我可以手动运行那些相同的测试,并且它们全部通过.
我知道这可能不足以使某人直接解决问题,但我什至不知道如何调查此问题.尝试创建或打开内存映射文件时,什么样的事情可能导致“句柄无效”消息?
解决方法:
它被记录为CreateFileMapping()的错误代码,该文件是创建内存映射文件的基础winapi函数:
If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.
因此,请选择一个好的随机名称以避免此错误.您可以从Visual Studio中获得一个:工具创建GUID,选项4.它是全局唯一的.
内容总结
以上是互联网集市为您收集整理的C#-MemoryMappedFile.CreateOrOpen引发句柄无效全部内容,希望文章能够帮你解决C#-MemoryMappedFile.CreateOrOpen引发句柄无效所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。