How to set test TCP connection timeout?

前端 未结 3 1439
梦毁少年i
梦毁少年i 2020-12-31 08:16

I try to test TCP connection with the following code.

System.Threading.Thread t = new System.Threading.Thread(() =>
{      
    using (TcpClient client =          


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 09:15

    Much too late to be of use to the OP but for anybody else still finding this page from a search, you can solve this using the asynchronous programming features introduced in .Net 4.5.

    var hostname = "127.0.0.1";
    var port = 123;
    var timeout = TimeSpan.FromSeconds(3);
    var client = new TcpClient();
    if (!client.ConnectAsync(hostname, port).Wait(timeout))
    {
        // timed out
    }
    

提交回复
热议问题