我正在努力寻找实现命名管道IPC的最佳方法,并使用强大的超时管理。我并不是说建立连接超时,而是读/写流超时。
我发现的所有示例都没有超时实现。
有人可以给我一个有效的例子和/或指出一个展示这个的例子吗?
答案 0 :(得分:3)
您可能需要做的是使用NamedPipeClientStream.BeginRead
和NamedPipeClientStream.BeginWrite
进行异步读写;然后,将使用一个计时器来检测数据何时未被发送或接收一段时间。
每当发送或接收数据时,DateTime
字段将设置为DateTime.Now
,并且每次执行定时器都将检查该字段以确定是否发生超时。如果出现这种情况,可以关闭NamedPipeClientStream
,并且可以捕获NamedPipeClientStream.EndRead
和NamedPipeClientStream.EndWrite
的例外情况。
我还没有准备好工作示例,但是如果你需要的话,我会开始工作。希望这会在平时帮助你。
这是一些非常粗略的示例代码。还需要做更多工作,例如实现IDisposable
和添加写入方法。但这应该有助于说明这个想法。最好将此代码用作模型,而不是直接使用它。我已经测试了代码,看它是否可以读取。
//this is a very rough model of how to do it. a lot more would need to be implemented
//i'm assuming you plan to continuously read from it. i can think up another example if you're not
//also not thread safe
public class MyPipeClient
{
NamedPipeClientStream PipeClient = new NamedPipeClientStream("testpipe1");
Timer TimeoutTimer;
DateTime LastRead;
const int TimeoutSeconds = 120; //2 mins
//will connect and start receiving
public void Connect()
{
PipeClient.Connect();
LastRead = DateTime.Now;
TimeoutTimer = new Timer(TimeoutCheck, this, 0, 1000); //check every second
Read(this);
}
public void Disconnect()
{
PipeClient.Close(); PipeClient = null;
TimeoutTimer.Dispose(); TimeoutTimer = null;
}
static void Read(MyPipeClient client)
{
PipeState state = new PipeState(client);
try
{
client.PipeClient.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallback, state);
}
catch (InvalidOperationException) //disconnected/disposed
{
return;
}
}
static void ReadCallback(IAsyncResult ar)
{
PipeState state = (PipeState)ar.AsyncState;
MyPipeClient client = state.Client;
client.LastRead = DateTime.Now;
int bytesRead;
try
{
bytesRead = client.PipeClient.EndRead(ar);
}
catch (IOException) //closed
{
return;
}
if (bytesRead > 0)
{
byte[] data = state.Buffer;
//TODO: something
}
else //i've never used pipes, so i'm assuming this behavior exists with them
{
client.Disconnect();
return;
}
Read(client);
}
static void TimeoutCheck(object state)
{
MyPipeClient client = (MyPipeClient)state;
TimeSpan timeSinceLastRead = DateTime.Now - client.LastRead;
if (timeSinceLastRead.TotalSeconds > TimeoutSeconds)
{
client.Disconnect();
}
}
}
class PipeState
{
public byte[] Buffer = new byte[4096];
public MyPipeClient Client;
public PipeState(MyPipeClient client)
{
Client = client;
}
}