Error attempting asynchronous connection

2

I am trying to do this in order not to crash the application while waiting for the server to accept the connection. I saw what you can do with async and await . But when trying to use them to wait for the connection without crashing, the program returns infinitely a Exception :

  

Exception thrown: 'System.NullReferenceException' in MessengerTcpIp.exe

And it gets all stuck. It gives this problem at the time of waiting for the server to respond.

Code:

private async void ConnectServer()
        {
            try
            {
                server = IPAddress.Parse(serverAddr.Text);
                port = 12303;
                user = new TcpClient();
                connBtn.Text = "Aguardando conexão";
                await user.ConnectAsync(server, port);
                strWriter = new StreamWriter(user.GetStream());
                strReader = new StreamReader(user.GetStream());
                strWriter.AutoFlush = true;
                StrWriter.WriteLine(email.Text);
                StrWriter.WriteLine(password.Text);
                var SvResponse = await strReader.ReadLineAsync();
                if(SvResponse == "ok")
                {
                    userInfo.AppendText("Conectado com sucesso.");
                    connBtn.Text = "Conectado";
                } 
                else
                {
                    MessageBox.show("Falha ao se conectar.");
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("Exception:" + err.Message, "Erro de conexão.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                connBtn.Text = "Conectar";
            }

        }

Calling button:

private void Conectar_Click(object sender, EventArgs e)
{
    ConnectServer();
}
    
asked by anonymous 09.10.2017 / 04:42

1 answer

1

You have created an asynchronous method, but you are not expecting it to finish execution.

Change the code to the following:

private void Conectar_Click(object sender, EventArgs e)
{
    Task.Run(ConnectServer()).Wait();
}

And see this my answer about call async with async and await . It has a pretty cool example showing how it works and what happens when badly employed.

    
09.10.2017 / 09:22