NamedPipeServerStream读/写器线程C#

时间:2011-10-22 21:46:38

标签: c# thread-safety named-pipes

我正在尝试在两个线程(读者和编写者)之间共享NamedPipeServerStream实例。该程序有效但当我尝试创建ServerProcess对象的两个实例时,编写器线程开始挂起。我哪里错了?

任何建议都将不胜感激。

产卵方法如下:

 public class ServerPrcoess
 {
    private static NamedPipeServerStream m_NamePipeHandle;
    public  static void StartPipe()
    {
        int i = 0;

        Thread[] OPCServerReader = new Thread();
        Thread[] OPCServerWriter = new Thread();

        m_NamePipeHandle = new NamedPipeServerStream(PIPENAME, PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

        m_NamePipeHandle.WaitForConnection();

        OPCServerReader = new Thread(PipeReaderThread);
        OPCServerReader.IsBackground = true;
        OPCServerReader.Start(i);

        Thread.Sleep(1000);

        OPCServerWriter = new Thread(PipeWriterThread);
        OPCServerWriter.IsBackground = true;
        OPCServerWriter.Start();
      }
 }

读者线程与下面类似,并使用管道句柄创建二进制读取器对象: -

private  static void PipeReaderThread(object ThreadNo)
{
     Console.WriteLine("Reader Thread Number: {0}", (int)ThreadNo);
     try
     {

         StreamOPCMessageReader oMsgReader = new StreamOPCMessageReader(m_NamePipeHandle);

            ...

并且编写器线程使用相同的管道句柄执行等效操作。

private static void PipeWriterThread(object _ThreadNo)
{         
     int ThreadNo  = Thread.CurrentThread.ManagedThreadId;
     try
     {               
        StreamOPCMessageWriter oMsgWriter = new StreamOPCMessageWriter(m_NamePipeHandle);

1 个答案:

答案 0 :(得分:0)

您无法使用相同名称创建多个NamedPipeServerStream实例( PIPENAME )。