Home > other >  MessageQueue for WPF for interprocess communication
MessageQueue for WPF for interprocess communication

Time:07-02

Is there a way to create a message queue for a WPF .NET 6.0 program? I saw documentation for MSMQ but it looks like that is not supported in .NET 6.0.

I want to be able to communicate to another instance of the same program. What would be the best way to do that?

CodePudding user response:

The best alternative I found was named pipes in System.IO.Pipes.

Example of sending/receiving a string:

        private bool PipeSend(string message)
        {
            using (NamedPipeServerStream namedPipeServer
                = new NamedPipeServerStream(ConfigurationManager.AppSettings["AppGUID"]!))
            {
                // In this example I check if there is a client ready to receive the 
                // data otherwise I cancel the connection.
                CancellationTokenSource cts = new();
                namedPipeServer.WaitForConnectionAsync(cts.Token);
                Thread.Sleep(500);
                if (namedPipeServer.IsConnected)
                {
                    byte[] buffer = message.Select(c => (byte)c).ToArray();
                    namedPipeServer.Write(buffer, 0, buffer.Length);
                    return true;
                }
                else
                {
                    cts.Cancel();
                    return false;
                }
            }
        }

        private void PipeReceive()
        {
            using (NamedPipeClientStream namedPipeClient
                = new NamedPipeClientStream(ConfigurationManager.AppSettings["AppGUID"]!))
            {
                namedPipeClient.Connect();
                if (namedPipeClient.IsConnected)
                {
                    List<char> buffer = new();

                    int b = namedPipeClient.ReadByte();
                    while (b != -1)
                    {
                        buffer.Add((char)b);
                        b = namedPipeClient.ReadByte();
                    }

                    string message = new(buffer.ToArray());
                    // Do something with the message
                }
            }
        }
  • Related