C# How do I stop a tcpClient.Connect() process when i'm ready for the program to end? It just sits there for like 10 seconds!

折月煮酒 提交于 2019-11-29 07:42:00

Adding a check within your connection process to cancel it if the program is exiting should help.

Try adding this in CreateConnection() inside your while(!success) loop but before your try block:

if(RequestExitConnectionThread)
{
    break;
}

Here's an example of an asynchronous BeginConnect() call:

myTcpClient.BeginConnect("localhost", 80, OnConnect, null);

OnConnect function:

public static void OnConnect(IAsyncResult ar)
{
    // do your work
}
JoanComasFdz

Sorry, after testing it: NO, it does not use an async waithandle, it blocks the process :(

I prefer this solution, which also blocks the process but only by the period you specify, in this case 5 seconds:

using (TcpClient tcp = new TcpClient())  
{  
    IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 80, null, null);  
    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;  
    try 
    {  
       if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))  
       {  
           tcp.Close();  
           throw new TimeoutException();  
       }  

        tcp.EndConnect(ar);  
    }  
    finally 
    {  
        wh.Close();  
    }  
}

From: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/2281199d-cd28-4b5c-95dc-5a888a6da30d

The following example uses both async connection and async timeout control:

var tcp = new TcpClient();
var ar = tcp.BeginConnect(Ip, Port, null, null);
Task.Factory.StartNew(() =>
{
    var wh = ar.AsyncWaitHandle;
    try
    {
        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
        {
            // The logic to control when the connection timed out
            tcp.Close();
            throw new TimeoutException();
        }
        else
        {
            // The logic to control when the connection succeed.
            tcp.EndConnect(ar);
         }
     }
     finally
     {
         wh.Close();
     }
});

connect with timeout of 2000 ms:

AutoResetEvent connectDone = new AutoResetEvent( false );
TcpClient client = new TcpClient();
client.BeginConnect(
    "127.0.0.1", 80,
    new AsyncCallback(
        delegate( IAsyncResult ar ) {
            client.EndConnect( ar );
            connectDone.Set();
        }
    ), client
);
if( !connectDone.WaitOne( 2000 ) ) {
    Console.WriteLine( "network connection failed!" );
    Environment.Exit( 0 );
}
Stream stream = client.GetStream();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!