0

I have written a simple Windows Forms application however the TcpClient connection blocks the UI. I understand that I need to use a asynchronous connection however I can't work out how to convert the below code to be an asynchronous connection using the Microsoft documentation.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private TcpClient client;

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var client = new TcpClient())
            {
                client.Connect("127.0.0.1", 1234);

                using (var stream = client.GetStream())
                using (var writer = new StreamWriter(stream))
                using (var reader = new StreamReader(stream))
                {
                    while (client.Connected)
                    {
                        var data = reader.ReadLine();

                        if (data != null)
                        {
                            ...
                        }
                    }
                }
            }
        }

        private void disconectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            client.Close();
        }
    }
}
  • You probably need a BackgroundWorker – ADyson Sep 23 '20 at 20:37
  • [TcpClient.ConnectAsync](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.connectasync) + [StreamReader.ReadLineAsync](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.readlineasync) + [StreamWriter.WriteLineAsync](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.writelineasync) or [StreamWriter.WriteAsync](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.writeasync) – Jimi Sep 24 '20 at 03:29

0 Answers0