【问题标题】:TcpClient Connect delayTcpClient 连接延迟
【发布时间】:2015-08-03 10:34:50
【问题描述】:

我迷路了。当我想在我的 Form1 中编辑某些内容时,我必须在编辑后执行命令 Form1.show();所以我不编辑打开的表格,而是一些不可见的新表格。我认为它在构造函数中的某个地方,但我不知道在哪里。 请帮忙

Cli 类:

    public class Cli
{
    Form1 frm;
    TcpClient tcpclnt = new TcpClient();

    public Cli()
    {


    }
    public void Connect()
    {
        frm = new Form1();
        try
        {

            frm.debug.Text = "Connecting";

            tcpclnt.Connect("127.0.0.1", 8001);
            // use the ipaddress as in the server program
            frm.debug.Text = "Connected";

        }
        catch (Exception e)
        {
            frm.debug.Text=("Error..... " + e.StackTrace);
            frm.Show();
        }...

Form1 类:

    public partial class Form1 : Form
{
    Cli client;
    public int pocet = 0;
    public Form1()
    {
        InitializeComponent();
        client  =new Cli();
        Random rnd = new Random();

        pocet = rnd.Next(23, 10000);
        if (pocet % 2 == 1)
        {
            label1.Text = "HRAJEŠ";
        }
        else { label2.Text = "HRAJEŠ"; }



    }...

【问题讨论】:

  • 如下回答 tcpclnt.Connect("127.0.0.1", 8001);造成这个错误,除了创建一个新的赢表是不好的做法。解耦视图和业务逻辑层

标签: c# .net winforms asynchronous tcpclient


【解决方案1】:

没有无限循环,我认为您遇到了延迟,因为它正在等待TcpClient.Connect() 返回。

改用异步连接。

frm.debug.Text = "Connecting";

var client = new TcpClient();
var result = client.BeginConnect("127.0.0.1", 8001, null, null);

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

if (!success)
{
    throw new Exception("Failed to connect.");
}

// we have connected

frm.debug.Text = "Connected";
client.EndConnect(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多