CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task tserver = Task.Run(() =>
{
NamedPipeServer server = new NamedPipeServer();
server.dowork(token);
});
Task tclient = Task.Run(() =>
{
NamedPipeClient client = new NamedPipeClient();
client.dowork();
});
await Task.Delay(1000);
cts.Cancel();
await Task.WhenAll(tserver,tclient);
await Task.Delay(2000);
class NamedPipeServer
{
string pipename = "testpipe";
public async Task dowork(CancellationToken token)
{
try
{
using(NamedPipeServerStream serverPipe = new NamedPipeServerStream(pipename, PipeDirection.InOut))
{
"Server: Wating for client connection...".Dump();
await serverPipe.WaitForConnectionAsync(token);
"Server: Client connected".Dump();
int cnt = 0;
using(StreamReader reader = new StreamReader(serverPipe))
using(StreamWriter writer = new StreamWriter(serverPipe))
{
while (true)
{
string receivedMessage = await reader.ReadLineAsync();
if(receivedMessage == null)
{
cnt++;
if(cnt > 10) break;
}
else
{
$"Server: Received message: {receivedMessage}".Dump();
}
await Task.Delay(1);
}
}
}
}
catch
{
}
}
}
class NamedPipeClient
{
string pipename = "testpipe";
public async Task dowork()
{
try
{
using(NamedPipeClientStream client = new NamedPipeClientStream(".",pipename, PipeDirection.InOut))
{
"Client: Connecting to server".Dump();
await client.ConnectAsync();
"Client: Connected to server".Dump();
using(StreamWriter writer = new StreamWriter(client))
{
string sendbuff = "hello world";
await writer.WriteLineAsync(sendbuff);
"Client: Sending to Server".Dump();
await writer.FlushAsync();
}
}
}
catch
{
}
}
}
标签:Task,Dump,C#,NamedPipe,await,传输,client,using,new
From: https://www.cnblogs.com/senya8030/p/18047544