// ############################### TcpClient TcpClient; //From StackOverflow post //My post with the method that times out after 30 seconds public async Task ConnectAsyncMy(string host, int port) { var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(65)); try { TcpClient = new TcpClient(); await TcpClient.MyConnectAsync(host, port, cancel.Token); //Connected, do real work } catch (OperationCanceledException eC) { //Connection was cancelled Trace.WriteLine($"AA {eC.Message}"); } catch (Exception e) { //Connection was cancelled Trace.WriteLine($"BB {e.Message}"); }; } //private async Task btnAsynConnect_Click(object sender, EventArgs e) private async void btnAsynConnect_Click(object sender, EventArgs e) { //using (var tcpClient = new TcpClient()) //{ // await RunTask(tcpClient.ConnectAsync("127.0.0.1", 6001), 15000, cancellationToken: CancellationToken.None); //} try { int z = 0; //All this is running on the UI thread //... Trace.WriteLine($"AAA"); //Call the async method on a worker thread //await causes the current method to stop until the async work is complete //But the UI thread will resume so the user doesn't get a blocked UI await ConnectAsyncMy("127.0.0.1", 7775); //The async method is complete and this code is now running on the UI thread again //... Trace.WriteLine($"BBBB"); } catch (ObjectDisposedException eDisposedException) { Trace.WriteLine("Caught: {0}", eDisposedException.Message); } catch (Exception ee2) { Trace.WriteLine($"{ee2.Message}"); }; } public async Task RunTask(Task task, int timeout = 0, CancellationToken cancellationToken = default(CancellationToken)) { await RunTask((Task)task, timeout, cancellationToken); //task.Wait(); return await task; } public async Task RunTask(Task task, int timeout = 0, CancellationToken cancellationToken = default(CancellationToken)) { if (timeout == 0) timeout = -1; var timeoutTask = Task.Delay(timeout, cancellationToken); await Task.WhenAny(task, timeoutTask); //task.Wait(cancellationToken); //task.Wait(timeout); //task.Wait(); cancellationToken.ThrowIfCancellationRequested(); if (timeoutTask.IsCompleted) throw new TimeoutException(); await task; }