A community member has associated this post with a similar question:
C# TcpClient/TcpListener / Full Duplex Communication / Sample

Only moderators can edit this content.

C# AsyncWaitHandle.WaitOne - Socket

Markus Freitag 3,786 Reputation points
2023-02-06T18:16:22.42+00:00

Hello,

Why doesn't the connection attempt wait 15 seconds?

How can I achieve that the client gets up to 15 seconds for a connection?

Socket or TcpClient. Thanks for your help!

//Create IP address and port number;
System.Net.IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Determine whether you can connect to the server
try
{
	//socket.Connect(iPEndPoint);

	var result = socket.BeginConnect(iPEndPoint, null, null);
	bool success = result.AsyncWaitHandle.WaitOne(15000, true);
	if (success)
	{
		socket.EndConnect(result);
	}
	else
	{
		socket.Close();
		throw new SocketException(10060); // Connection timed out.
	}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,375 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,249 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,281 Reputation points
    2023-02-09T23:02:00.3333333+00:00

    You already asked a similar question here. Using BeginConnect is not a recommended approach at all. Using ConnectAsync with an auto-cancelling source as discussed in the other thread solves the problem you are having here.

    0 comments No comments