您不能超时或取消异步Socket
操作。
所有你能做的就是开始自己Timer
其封闭Socket
-the回调将被立即调用,EndX
功能会回来与ObjectDisposedException
如果你调用它。以下是一个示例:
using System;
using System.Threading;
using System.Net.Sockets;
class AsyncClass
{
Socket sock;
Timer timer;
byte[] buffer;
int timeoutflag;
public AsyncClass()
{
sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
buffer = new byte[256];
}
public void StartReceive()
{
IAsyncResult res = sock.BeginReceive(buffer, 0, buffer.Length,
SocketFlags.None, OnReceive, null);
if(!res.IsCompleted)
{
timer = new Timer(OnTimer, null, 1000, Timeout.Infinite);
}
}
void OnReceive(IAsyncResult res)
{
if(Interlocked.CompareExchange(ref timeoutflag, 1, 0) != 0)
{
// the flag was set elsewhere, so return immediately.
return;
}
// we set the flag to 1, indicating it was completed.
if(timer != null)
{
// stop the timer from firing.
timer.Dispose();
}
// process the read.
int len = sock.EndReceive(res);
}
void OnTimer(object obj)
{
if(Interlocked.CompareExchange(ref timeoutflag, 2, 0) != 0)
{
// the flag was set elsewhere, so return immediately.
return;
}
// we set the flag to 2, indicating a timeout was hit.
timer.Dispose();
sock.Close(); // closing the Socket cancels the async operation.
}
}
我找到了类似的答案。 http://stackoverflow.com/questions/1231816/net-async-socket-timeout-check-thread-safety。 这个想法是有一个单一的定时器来照顾所有现有的连接来检查它是否超时。 – kevin 2011-05-13 01:38:37