BeginConnect
is an async call. When you call that method it returns immediately so the caller isn't blocked. Behind the scenes a connection is made to the remote server. As soon as the handshaking is done then your callback is called to let you know you now have a connection to the remote endpoint. In many cases this should be really fast but if the server is slow to respond or the network is swamped then it could take a little longer. The purpose of this method is to allow your code to move on and do other things while waiting (such as displaying a connecting message to the user).
When the callback gets called you need to call EndConnect
. Every Begin...
method has a corresponding End...
method. The Begin
call has to allocate resources for the async callback. The End
call tells the runtime that those resources can be cleaned up. If you don't call this method then you end up leaking the resources that were allocated. You just need to call it at some point during your callback. Most people tend to call this early in the callback in case the callback fails.
Note that you should really never be using the Begin/End
methods. These are provided for backwards compatibility and to provide a thin wrapper over the underlying winsock library that supports async. This is how async used to work. For current code you should be using the ConnectAsync method instead. Task-based async is the preferred approach in all cases now. It requires less code and it just works. The equivalent code would look something like this.
async void ConnectAsync (...)
{
await socket.ConnectAsync(...);
//Connected so do real work now
}
It looks like you want to give up if you cannot connect within 30 seconds. You can do that by passing a CancellationToken
that auto-cancels after 30 seconds.
async void ConnectAsync (...)
{
var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
await socket.ConnectAsync(..., cancel.Token);
//Connected, do real work
} catch (OperationCanceledException)
{
//Connection was cancelled
};
}