Skip to content

Commit

Permalink
Reduce overhead in ManagedNamedPipeClient during connection loop
Browse files Browse the repository at this point in the history
The implementation of `NamedPipeClientStream` has some
 egregious use of `SpinOnce`:

https://github.com/dotnet/runtime/blob/d59af2cf097acb100ad6a9cba652be34be6f4a2e/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs#L151-L155

This adds perceivable overhead to the connect process, which we really
don't want on a background thread. It is especially noticeable when
discord is not running and the reconnect process is constantly running
in the background.

To get around this, we can request a connect timeout of 0 ms from the underlying API.
Checking the implementations, this seems like a valid method, as long as
there is external retry logic in place (which there is in the local
class).

Tested on Windows, macOS and linux.
  • Loading branch information
peppy committed Jul 13, 2023
1 parent db3667e commit 426b752
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion DiscordRPC/IO/ManagedNamedPipeClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ private bool AttemptConnection(int pipe, bool isSandbox = false)
{
Logger.Info("Attempting to connect to '{0}'", pipename);
_stream = new NamedPipeClientStream(".", pipename, PipeDirection.InOut, PipeOptions.Asynchronous);

// Intentionally use a timeout of 0 here to avoid spinlock overhead.
// We are already performing local retry logic, so this is not required.
_stream.Connect(1000);

//Spin for a bit while we wait for it to finish connecting
Expand Down Expand Up @@ -378,7 +381,7 @@ public void Close()
return;
}

//flush and dispose
//flush and dispose
try
{
//Wait for the stream object to become available.
Expand Down

0 comments on commit 426b752

Please sign in to comment.