Skip to content

Commit 9f69556

Browse files
committed
Improve ConnectWithTimeout method in PooledSocket
1 parent 443a6be commit 9f69556

File tree

1 file changed

+9
-16
lines changed

1 file changed

+9
-16
lines changed

Enyim.Caching/Memcached/PooledSocket.cs

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -59,28 +59,21 @@ public PooledSocket(DnsEndPoint endpoint, TimeSpan connectionTimeout, TimeSpan r
5959

6060
private void ConnectWithTimeout(Socket socket, DnsEndPoint endpoint, int timeout)
6161
{
62-
var completed = new AutoResetEvent(false);
63-
6462
var args = new SocketAsyncEventArgs();
6563
args.RemoteEndPoint = endpoint;
66-
args.Completed += OnConnectCompleted;
67-
args.UserToken = completed;
68-
socket.ConnectAsync(args);
6964

70-
if (!completed.WaitOne(timeout) || !socket.Connected)
65+
using (var mres = new ManualResetEventSlim())
7166
{
72-
using (socket)
67+
args.Completed += (s, e) => mres.Set();
68+
if (socket.ConnectAsync(args))
7369
{
74-
throw new TimeoutException("Could not connect to " + endpoint);
70+
if(!mres.Wait(timeout))
71+
{
72+
throw new TimeoutException("Could not connect to " + endpoint);
73+
}
7574
}
76-
}
77-
}
78-
79-
private void OnConnectCompleted(object sender, SocketAsyncEventArgs args)
80-
{
81-
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
82-
handle.Set();
83-
}
75+
}
76+
}
8477

8578
public Action<PooledSocket> CleanupCallback { get; set; }
8679

0 commit comments

Comments
 (0)