Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C#内存共享读取和写入 #88

Open
landv opened this issue Aug 14, 2024 · 0 comments
Open

C#内存共享读取和写入 #88

landv opened this issue Aug 14, 2024 · 0 comments

Comments

@landv
Copy link
Owner

landv commented Aug 14, 2024

内存共享读取

class Program
{
	static void Main()
	{
		// 打开一个现有的内存映射文件
		using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("sharedMemory"))
		{
			// 创建一个视图流来访问内存映射文件
			using (MemoryMappedViewStream stream = mmf.CreateViewStream())
			{
				// 读取数据从内存映射文件
				byte[] data = new byte[1024];
				int bytesRead = stream.Read(data, 0, data.Length);
				string message = Encoding.UTF8.GetString(data, 0, bytesRead);
				Console.WriteLine("Data read from shared memory: " + message);
			}
		}

	}
}

内存共享写入

class Program
{
	static void Main()
	{
		// 创建或打开一个内存映射文件
		using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("sharedMemory", 1024))
		{
			// 创建一个视图流来访问内存映射文件
			using (MemoryMappedViewStream stream = mmf.CreateViewStream())
			{
				// 写入数据到内存映射文件
				byte[] data = Encoding.UTF8.GetBytes("Hello from Process 1");
				stream.Write(data, 0, data.Length);
				Console.WriteLine("Data written to shared memory.");
			}
		}

		//Console.WriteLine("Press any key to exit...");
		//Console.ReadKey();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant