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();
}
}
}