英文:
.NET/C# - AnonymousPipeServerStream/AnonymousPipeClientStream not working
问题
我想在AnonymousPipeServerStream和AnonymousPipeClientStream之间交换数据。
这段代码不起作用。它在Join上阻塞。
Console.WriteLine("> " + text2);
从未被调用。
你有任何想法吗?
谢谢。
using (AnonymousPipeServerStream pipeout = new AnonymousPipeServerStream(PipeDirection.Out))
{
using (AnonymousPipeClientStream pipein = new AnonymousPipeClientStream(PipeDirection.In,
pipeout.GetClientHandleAsString()))
{
byte[] res;
Thread t = new Thread(() =>
{
using (MemoryStream x = new MemoryStream())
{
pipein.CopyTo(x);
res = x.ToArray();
string text2 = Encoding.UTF8.GetString(res);
Console.WriteLine("> " + text2);
}
});
t.Start();
string text = "hello !";
using (MemoryStream x = new MemoryStream(Encoding.UTF8.GetBytes(text)))
{
x.CopyTo(pipeout);
}
t.Join();
}
}
英文:
I would like to exchange data between AnonymousPipeServerStream and AnonymousPipeClientStream
This code is not working. It is block on Join.
Console.WriteLine("> " + text2);
is never called
Do you have any idea ?
Thanks
using (AnonymousPipeServerStream pipeout = new AnonymousPipeServerStream(PipeDirection.Out))
{
using (AnonymousPipeClientStream pipein = new AnonymousPipeClientStream(PipeDirection.In,
pipeout.GetClientHandleAsString()))
{
byte[] res;
Thread t = new Thread(() =>
{
using (MemoryStream x = new MemoryStream())
{
pipein.CopyTo(x);
res = x.ToArray();
string text2 = Encoding.UTF8.GetString(res);
Console.WriteLine("> " + text2);
}
});
t.Start();
string text = "hello !";
using (MemoryStream x = new MemoryStream(Encoding.UTF8.GetBytes(text)))
{
x.CopyTo(pipeout);
}
t.Join();
}
}
答案1
得分: 0
你需要关闭出站管道,否则客户端将一直等待更多数据。
pipeout.Close();
t.Join()
或者你可以在等待线程之前关闭using
。 (你需要将Thread t;
的声明移到using
外部)
}
t.Join();
但我不确定为什么你要使用这样的代码。对于进程内通信,最好使用某种线程安全的队列。此外,你应该使用任务而不是线程。
英文:
You need to close the outbound pipe, otherwise the client side will just keep waiting for more data
pipeout.Close();
t.Join()
Alternatively you can close the using
before waiting on the thread. (you need to move the declaration of Thread t;
outside the using
)
}
t.Join();
But I'm not sure why you would want to use such code. For in-process communication it would be wiser to just use some kind of thread-safe queue. Furthermore, you should probably use tasks not threads.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论