我正在使用命名管道在应用程序之间传递某些消息。
我的管道客户端读取使用PipeStream.ReadByte()
从服务器发送的消息。这会阻塞正在运行的线程。
这种行为通常很好,但是,在阻塞该线程时,我无法找到一种处置该线程的好方法。当客户端退出时,该线程将保持 Activity 状态,直到流获取一些数据,并允许它再次检查循环变量。在服务器静默的情况下,线程将继续存在。Thread.Abort()
无效。
在移至ReadByte()
方法之前,有没有办法检查数据流? PipeStream.Length
抛出UnsupportedException
。
最佳答案
一种解决方案是使用异步I/O和任务而不是专用线程,并使用CancelationToken
中止挂起的IO。下面的代码段显示了一个简化的示例,该代码段基于此答案https://stackoverflow.com/a/29423042/2573395,但是对管道操作进行了一些修改(在这种情况下,异步等待每个消息的连接)。请注意,我不是命名管道的专家,因此可能会有更多的最佳方法。
public class MyPipeReader
{
private string _pipeName;
public MyPipeReader(string pipeName)
{
_pipeName = pipeName;
}
public async Task ReceiveAndProcessStuffUntilCancelled(CancellationToken token)
{
var received = new byte[4096];
while (!token.IsCancellationRequested)
{
using (var stream = CreateStream())
{
try
{
if (await WaitForConnection(stream, token))
{
var bytesRead = 0;
do {
bytesRead = await stream.ReadAsync(received, 0, 4096, token).ConfigureAwait(false);
} while (bytesRead > 0 && DoMessageProcessing(received, bytesRead));
if (stream.IsConnected)
stream.Disconnect();
}
}
catch (OperationCanceledException)
{
break; // operation was canceled.
}
catch (Exception e)
{
// report error & decide if you want to give up or retry.
}
}
}
}
private NamedPipeServerStream CreateStream()
{
return new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
}
private async Task<bool> WaitForConnection(NamedPipeServerStream stream, CancellationToken token)
{
// We can't simply use 'Task.Factory.FromAsync', as that is not cancelable.
var tcs = new TaskCompletionSource<bool>();
var cancelRegistration = token.Register(() => tcs.SetCanceled());
var iar = stream.BeginWaitForConnection(null, null);
var rwh = ThreadPool.RegisterWaitForSingleObject(iar.AsyncWaitHandle, delegate { tcs.TrySetResult(true); }, null, -1, true);
try
{
await tcs.Task.ConfigureAwait(false);
if (iar.IsCompleted) {
stream.EndWaitForConnection(iar);
return true;
}
}
finally
{
cancelRegistration.Dispose();
rwh.Unregister(null);
}
return false;
}
private bool DoMessageProcessing(byte[] buffer, int nBytes)
{
try
{
// Your processing code.
// You could also make this async in case it does any I/O.
return true;
}
catch (Exception e)
{
// report error, and decide what to do.
// return false if the task should not
// continue.
return false;
}
}
}
class Program
{
public static void Main(params string[] args)
{
using (var cancelSource = new CancellationTokenSource())
{
var receive = new MyPipeReader("_your_pipe_name_here_").ReceiveAndProcessStuffUntilCancelled(cancelSource.Token);
Console.WriteLine("Press <ENTER> to stop");
Console.ReadLine();
cancelSource.Cancel();
receive.Wait();
}
}
}
关于c# - 确定PipeStream是否有数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29437319/