Skip to content

Instantly share code, notes, and snippets.

@djhohnstein
Forked from AArnott/ConsoleApp.csproj
Created September 4, 2021 04:52
Show Gist options
  • Save djhohnstein/2188b0b85fc228752abf948e5713e42d to your computer and use it in GitHub Desktop.
Save djhohnstein/2188b0b85fc228752abf948e5713e42d to your computer and use it in GitHub Desktop.
Async named pipes example
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>exe</OutputType>
<TargetFrameworks>net472;net5.0-windows</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.IO.Pipes.AccessControl" Version="5.0.0" />
</ItemGroup>
</Project>
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
const string pipeName = @"testpipe";
Task serverTask = RunServerAsync(pipeName);
Task clientTask = RunClientAsync(pipeName);
Task.WaitAll(serverTask, clientTask);
}
private static async Task RunServerAsync(string pipeName)
{
PipeSecurity security = new PipeSecurity();
security.AddAccessRule(new PipeAccessRule($"{Environment.UserDomainName}\\{Environment.UserName}", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
#if NET5_0 // .NET Core 3.1 does not support setting ACLs on named pipes.
NamedPipeServerStream serverPipe = NamedPipeServerStreamAcl.Create(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, security);
#elif NETFRAMEWORK
NamedPipeServerStream serverPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
#endif
await serverPipe.WaitForConnectionAsync();
var writer = new StreamWriter(serverPipe);
writer.AutoFlush = true;
var reader = new StreamReader(serverPipe);
await writer.WriteLineAsync("HELLO");
do
{
string line = await reader.ReadLineAsync();
if (line == "BYE" || line == null)
{
break;
}
await writer.WriteLineAsync(line);
} while (true);
serverPipe.Disconnect();
}
private static async Task RunClientAsync(string pipeName)
{
var clientPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
await clientPipe.ConnectAsync();
var writer = new StreamWriter(clientPipe);
writer.AutoFlush = true;
var reader = new StreamReader(clientPipe);
string line = await reader.ReadLineAsync();
if (line != "HELLO")
{
throw new ApplicationException("Error");
}
await writer.WriteLineAsync("1+1=2");
line = await reader.ReadLineAsync();
if (line != "1+1=2")
{
throw new ApplicationException("Error");
}
await writer.WriteLineAsync("BYE");
clientPipe.WaitForPipeDrain();
clientPipe.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment