[英]C# UWP Windows 10 Inter Process Communication with MemoryMappedFiles missing
[英]MemoryMappedFiles: persistance and inter process communication
我的memorymappedfiles有問題。
1)每次我請求一個文件(具有相同的名稱)時,我似乎都會得到一個新文件。 我寫的字節在下次訪問時不存在。 我只能通過持久化對象來解決此問題,我認為該對象是不需要的。
2)至於進程間的通信,我似乎總是為我擁有的2個進程得到2個不同的mmf對象,至少我看不到其他進程的變化。
兩個進程之間的FileName相同,並且在后續調用之間也保持相同。
該代碼已在http://www.abhisheksur.com/2012/02/inter-process-communication-using.html上稍作修改。
if條件中的“ read”參數及其后面的代碼也不會發生任何變化。
MemoryMappedFile file = null;
private MemoryMappedFile GetMemoryMapFile(bool read)
{
if (file != null)
return file;
var security = new MemoryMappedFileSecurity();
var everyone = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
// https://stackoverflow.com/a/5398398/586754
// everyone not present in german version..
security.SetAccessRule(
new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(everyone,
MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
MemoryMappedFile mmf;
if (read)
mmf = MemoryMappedFile.OpenExisting(FileName,
MemoryMappedFileRights.Read, //.ReadWriteExecute,
HandleInheritability.Inheritable);
else
mmf = MemoryMappedFile.CreateOrOpen(FileName,
this.length,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileOptions.None,
security,
HandleInheritability.Inheritable);
file = mmf;
return mmf;
}
public Transfer ReadEntry()
{
try
{
var mf = this.GetMemoryMapFile(read: true);
byte[] arr = new byte[length];
int offset = 0;
using (var accessor = mf.CreateViewAccessor(0, length))
{
accessor.ReadArray(offset, arr, offset, length);
}
var str = System.Text.Encoding.UTF8.GetString(arr, 0, length);
return Serializer.DeserializeFromText<Transfer>(str);
}
catch (Exception)
{
return new Transfer();
}
}
public void WriteEntry(Transfer entry)
{
try
{
var mf = this.GetMemoryMapFile(read: false);
int offset = 0;
var str = Serializer.SerializeToText(entry);
byte[] arr = System.Text.Encoding.UTF8.GetBytes(str);
using (var accessor = mf.CreateViewAccessor(0, this.length))
{
accessor.WriteArray(offset, arr, offset, arr.Length);
}
}
catch { }
}
編輯:參見答案,主要問題在於兩個進程分別是服務和用戶應用程序,因此規則略有不同。
另外,我不確定我是否真的需要“復雜的” GetMMF版本或只是簡單的版本,例如
private MemoryMappedFile GetMemoryMapFile()
{
var mmf = MemoryMappedFile.CreateOrOpen(FileName,
this.length);
return mmf;
}
我從未完全理解問題。我正在服務應用程序和用戶應用程序之間共享MMF。 這就是問題所在。
我想除了命名文件“ global \\ myfile”而不是“ myfile”,我所做的更改不必太多。
另請參閱https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/ebbc9cc3-03a4-4111-a157-fc5777929acb/shared-memory-between-a-service-and-a-user-app- in-windows-7?forum = windowssdk&prof =需要更多詳細信息(這是基於C ++的)。
我將看到將服務標簽添加到原始問題,以使將來的讀者更加清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.