app1
using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 多进程间通信1
{
class Program
{
static void Main(string[] args)
{
long capacity = 1 << 10 << 10;
//创建或者打开共享内存
var mmf = MemoryMappedFile.CreateOrOpen("testmap", capacity, MemoryMappedFileAccess.ReadWrite);
// bool mutexCreated;
//进程间同步
// Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated);
//通过指定的偏移量和大小来创建内存映射文件视图服务器
using (var viewAccessor = mmf.CreateViewAccessor(0, 10240)) //偏移量,可以控制数据存储的内存位置;大小,用来控制存储所占用的空间
{
//循环写入,使在这个进程中可以向共享内存中写入不同的字符串值
//while (true)
//{
Console.WriteLine("请输入一行要写入共享内存的文字:");
string input = Console.ReadLine();
//向共享内存开始位置写入字符串的长度
viewAccessor.Write(0, input.Length);
//向共享内存0位置写入字符
viewAccessor.WriteArray<char>(0, input.ToArray(), 0, input.Length);
// mutex.ReleaseMutex();
//}
}
Console.ReadKey();
}
}
}
app2
using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 多进程通信2
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入共享内存公用名(默认:testmap):");
string shareName = Console.ReadLine();
if (string.IsNullOrEmpty(shareName))
shareName = "testmap";
// Mutex mutex = Mutex.OpenExisting("testmapmutex");
long capacity = 1 << 10 << 10;
// mutex.WaitOne();
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(shareName))
{
//偏移量,可以控制数据存储的内存位置;大小,用来控制存储所占用的空间
MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor(0, capacity);
// mutex.WaitOne();
#region 方案一
//读取字符长度
int strLength = viewAccessor.ReadInt32(0);//3276849
char[] charsInMMf = new char[30];
//读取字符
viewAccessor.ReadArray<char>(0, charsInMMf, 0, 30);
Console.Clear();
Console.WriteLine(charsInMMf);
#endregion
}
// mutex.ReleaseMutex();
Thread.Sleep(200);
Console.ReadKey();
}
}
}