[英]Duplex named pipe in .NET gets stuck when writing during a read (async write)
我有一個 .NET 應用程序,它通過 NamedPipe 從其父 NodeJS 應用程序讀取消息,然后通過 stdout 寫回消息。 這工作正常,代碼大致如下所示:
節點:
const { spawn } = require("child_process");
const net = require("net");
const os = require("os");
let proc;
function main() {
const socket = await setUpNamedPipe();
proc.stdout.setEncoding("utf-8");
proc.stdout.on("data", message => {
message.trimEnd().split(os.EOL).forEach(m => {
console.log(m);
})
});
socket.write("message1" + os.EOL);
socket.write("message2" + os.EOL);
socket.write("message3" + os.EOL);
socket.write("message4" + os.EOL);
socket.write("message5" + os.EOL);
}
function setUpNamedPipe() {
const pipeName = "MyPipe";
const pipePath = `\\\\.\\pipe\\${pipeName}`;
let myResolve;
const somePromise = new Promise(r =>
{
myResolve = r;
});
const server = net.createServer((socket) =>
{
myResolve(socket);
});
server.listen(pipePath, () =>
{
proc = spawn("Test.exe", [pipeName]);
});
return somePromise;
}
.NET 應用程序:
using System.IO.Pipes;
public class Program
{
public static void ListenForMessages(TextReader reader)
{
while (true)
{
string message = reader.ReadLine();
if (message == null)
{
return;
}
Console.WriteLine(message);
}
}
public static void Main(string[] args)
{
string pipeName = args[0];
using NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut); // Just `In` doesn't work for some reason
client.Connect();
using TextReader reader = TextReader.Synchronized(new StreamReader(client));
Task.Factory.StartNew(() => ListenForMessages(reader), TaskCreationOptions.LongRunning).Wait();
}
}
如果我通過將proc.stdout.on("data", ...)
替換為socket.on("data", ...)
並在我的 .NET 應用程序中將其設置為名為TextWriter
的雙工,創建一個類似於我如何創建我的TextReader
:
using TextReader reader = TextReader.Synchronized(new StreamReader(client));
然后使用writer.WriteLine(...); writer.Flush();
writer.WriteLine(...); writer.Flush();
而不是Console.WriteLine
並在任務上寫,我沒有從我的 .NET 應用程序收到任何消息(除非我等待任務完成)。 我錯過了一步嗎?
大致像:
public static void ListenForMessages(NamedPipeClientStream client)
{
using TextWriter writer = TextWriter.Synchronized(new StreamWriter(client));
using TextReader reader = TextReader.Synchronized(new StreamReader(client));
while (true)
{
client.WaitForPipeDrain();
string message = reader.ReadLine();
if (message == null)
{
return;
}
Task.Run(() => {
writer.WriteLine(message);
writer.Flush();
}); // only works if I add `.Wait()`
}
}
public static void Main(string[] args)
{
string pipeName = args[0];
using NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
client.Connect();
Task.Factory.StartNew(() => ListenForMessages(client), TaskCreationOptions.LongRunning).Wait();
}
我只需要像這樣將PipeOptions.Asynchronous
標志傳遞給構造函數:
new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.