public static void ConnectWithTimeout(this TcpClient tc, string host, int port)
{
if (tc == null)
throw new ArgumentNullException
("tc");
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException
("host");
var ar = tc.BeginConnect(host, port, null, null);
var wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(tc.SendTimeout, false))
{
tc.Close();
throw new TimeoutException
();
}
tc.EndConnect(ar);
}
finally
{
wh.Close();
}
}
===============================================
var tc
= new TcpClient
();
tc.SendTimeout = 1000;
Helpers.ConnectWithTimeout(tc, "192.168.2.100", 6667);
System.TimeoutException: The operation has timed out.
at Local.Helpers.ConnectWithTimeout (System.Net.Sockets.TcpClient tc, System.String host, System.Int32 port) [0x0004d] in <84d4313427c14d0ebd16f3f379c8b3ed>:0
at <InteractiveExpressionClass>.Host (System.Object& $retval) [0x00000] in <839313ffb5aa47669729c09c35311b92>:0
at Mono.CSharp.Evaluator.Evaluate (System.String input, System.Object& result, System.Boolean& result_set) [0x00038] in <7a5ad0481e604e058be9486824118d15>:0
at Mono.CSharpShell.Evaluate (System.String input) [0x00000] in <23d81e17b05746d89659f83b8831d77b>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ObjectDisposedException: Safe handle has been closed
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef (System.Boolean& success) <0x7f7471aad510 + 0x000e8> in <7b0d87324cab49bf96eac679025e77d1>:0
at System.Threading.NativeEventCalls.SetEvent (Microsoft.Win32.SafeHandles.SafeWaitHandle handle) <0x7f7471a1ca20 + 0x0002a> in <7b0d87324cab49bf96eac679025e77d1>:0
at System.Threading.EventWaitHandle.Set () <0x7f7471a11c40 + 0x00009> in <7b0d87324cab49bf96eac679025e77d1>:0
at (wrapper remoting-invoke-with-check) System.Threading.EventWaitHandle.Set()
at System.IOAsyncResult.set_IsCompleted (System.Boolean value) [0x0001e] in <eeec8e88b1fc462e84ade7bf334d0c97>:0
at System.Net.Sockets.SocketAsyncResult.Complete () [0x00031] in <eeec8e88b1fc462e84ade7bf334d0c97>:0
at System.Net.Sockets.SocketAsyncResult.Complete (System.Exception e) [0x00007] in <eeec8e88b1fc462e84ade7bf334d0c97>:0
at System.Net.Sockets.Socket+<>c.<.cctor>b__313_4 (System.IOAsyncResult ares) [0x000d8] in <eeec8e88b1fc462e84ade7bf334d0c97>:0
at System.IOSelectorJob.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00000] in <eeec8e88b1fc462e84ade7bf334d0c97>:0
at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in <7b0d87324cab49bf96eac679025e77d1>:0
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () <0x7f7471a192f0 + 0x00005> in <7b0d87324cab49bf96eac679025e77d1>:0