HavenDV / H.Pipes

A simple, easy to use, strongly-typed, async wrapper around .NET named pipes.
MIT License
219 stars 26 forks source link

Different Send and Receive Types Info Request #32

Open NickSt opened 9 months ago

NickSt commented 9 months ago

I was wondering if there is a configuration I'm missing somewhere. Most examples seem to show using the same generic type for both sending and receiving. Typically though you rarely would receive an object of the same type as the one you are sending. Is there a way to configure H.Pipes to use different types. My current workaround is just including a string in the message that I then deserialize later, but this takes a way a lot of the value that this library adds as its not super hard just to do that to the standard pipe stream without adding another dependency to a project.

michalpaukert commented 7 months ago

I am using it like this `

   public async Task<T> SendIpcMessage<T>(PipeMessage message, CancellationToken cancellation = default) where T : PipeMessage
   {
       if (!_client.IsConnected)
       {
           await _client.ConnectAsync(cancellation).ConfigureAwait(false);
       }

       var messageResult = null as T;
       void ClientOnMessageReceived(object? sender, ConnectionMessageEventArgs<PipeMessage?> e)
       {
           if (e.Message is T result)
           {
               messageResult = result;
           }
       }

       try
       {
           _client.MessageReceived += ClientOnMessageReceived;

           _logger.LogDebug("Sending message {type} to pipe {name}", message.GetType(), _client.PipeName);
           await _client.WriteAsync(message, cancellation);

           while (!cancellation.IsCancellationRequested)
           {
               if (messageResult is { } outMessage)
               {
                   return outMessage;
               }
           }

           throw new TimeoutException();
       }
       catch (Exception e)
       {
           _logger.LogError(e, "Failed to send IPC message {type} to pipe {pipeName}", message.GetType(), _client.PipeName);
           throw;
       }
       finally
       {
           _client.MessageReceived -= ClientOnMessageReceived;
       }
   }

`