码迷,mamicode.com
首页 > Windows程序 > 详细

C#进程同步之管道通信

时间:2015-08-03 22:52:00      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

//write

using System;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Threading;

namespace memoryWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(".", "closePipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                namedPipeClientStream.Connect();
                StreamWriter sw = new StreamWriter(namedPipeClientStream);
                sw.WriteLine("Exit");
                sw.Flush();
                Thread.Sleep(1000);
                sw.Close();
            }
            catch (Exception ex)
            {
            }
        }
    }
}

//read

using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace memoryRead
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("closePipe", PipeDirection.InOut, 2);
                    namedPipeServerStream.WaitForConnection(); 
                    StreamReader sr = new StreamReader(namedPipeServerStream);
                    string recData = sr.ReadLine();
                    if (recData == "Exit")
                    {
                        Console.Write("success");
                    }
                    Thread.Sleep(1000);
                    sr.Close();
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}
单向管道允许一端写另一段读,双向管道允许一个进程既可以读又可以向管道写数据。
http://blog.sina.com.cn/s/blog_4b3485000101827p.html



版权声明:本文为博主原创文章,未经博主允许不得转载。

C#进程同步之管道通信

标签:

原文地址:http://blog.csdn.net/ilipan/article/details/47261879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!