C# C内存映射文件,应用程序挂起。发生了什么?
我正试图用内存映射文件为IPC编写简单的发送方/接收方类。 所以我的代码中有一个问题,但我不明白我在这里做错了什么:C# C内存映射文件,应用程序挂起。发生了什么?,c#,winforms,ipc,memory-mapped-files,C#,Winforms,Ipc,Memory Mapped Files,我正试图用内存映射文件为IPC编写简单的发送方/接收方类。 所以我的代码中有一个问题,但我不明白我在这里做错了什么: [Serializable] public struct MessageData { public int PID; public IntPtr HWND; public string ProcessName; public string ProcessTitle; } .... public static class MMF { pr
[Serializable]
public struct MessageData
{
public int PID;
public IntPtr HWND;
public string ProcessName;
public string ProcessTitle;
}
....
public static class MMF
{
private const int MMF_MAX_SIZE = 4096; // allocated memory for this memory mapped file (bytes)
private const int MMF_VIEW_SIZE = 4096; // how many bytes of the allocated memory can this process access
public static void Write()
{
var security = new MemoryMappedFileSecurity();
// Create a SecurityIdentifier object for "everyone".
SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
security.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyoneSid, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("Global\\mmf1", MMF_MAX_SIZE, MemoryMappedFileAccess.ReadWrite))
{
using (MemoryMappedViewStream mStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE))
{
var p = Process.GetCurrentProcess();
MessageData msgData = new MessageData();
msgData.HWND = p.MainWindowHandle;
msgData.PID = p.Id;
msgData.ProcessName = p.ProcessName;
msgData.ProcessTitle = p.MainWindowTitle;
// serialize the msgData and write it to the memory mapped file
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(mStream, msgData);
mStream.Flush();
mStream.Seek(0, SeekOrigin.Begin); // sets the current position back to the beginning of the stream
//MessageBox.Show("Done");
}
}
}
}
VisualStudio2015社区中的流程仍在继续。进程运行,但窗体接口没有响应。我只能暂停或停止这个过程。这是在使用MemoryMappedFile mmf=MemoryMappedFile.CreateOrOpenGlobal\\mmf1。。。绳子
我假设应用程序无法创建文件,但没有任何例外
所以,若我将地图名称更改为mmf1,而不使用全局前缀,则一切正常,应用程序工作正常。但据我所知,从和:
在文件映射对象名称前面加上Global\可以使进程相互通信,即使它们处于不同的终端服务器会话中
如果我理解正确,则需要前缀Global\来与任何应用程序交互我的内存映射文件,而不管它们运行的权限如何
特别是因为我正试图为每个人设置文件访问权限
UPD。此代码在Win 7/Win 8.1 x64上进行了测试。结果是相同的。您必须以管理员身份运行Visual Studio,才能使用全局\前缀创建内存映射文件。禁用您的反恶意软件产品,然后重试。感谢您的回复,但我在开发者PC上没有任何反邮件软件。并且此程序的用户是否也必须关闭反病毒软件,此应用程序才能工作?
...
private void button1_Click(object sender, EventArgs e)
{
MMF.Write();
}