C# 将Windows窗体TCP客户端连接转换为异步

C# 将Windows窗体TCP客户端连接转换为异步,c#,winforms,C#,Winforms,我已经编写了一个简单的Windows窗体应用程序,但是TcpClient连接会阻塞UI。我知道我需要使用异步连接,但是我无法使用Microsoft文档将下面的代码转换为异步连接 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using S

我已经编写了一个简单的Windows窗体应用程序,但是TcpClient连接会阻塞UI。我知道我需要使用异步连接,但是我无法使用Microsoft文档将下面的代码转换为异步连接

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

您可能需要一个BackgroundWorker++或