Error trying asynchronous connection

Asked

Viewed 257 times

2

I’m trying to do this way not to crash the application while waiting for the server to accept the connection. I saw that you can do with async and the await. But while trying to use them to wait for the connection without crashing, the program returns infinitely one Exception:

Exception thrown: 'System.Nullreferenceexception' in Messengertcpip.exe

And it gets all stuck. It gives this problem in time to wait 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";
            }

        }

Button that calls:

private void Conectar_Click(object sender, EventArgs e)
{
    ConnectServer();
}

1 answer

1

You created an asynchronous method, but you’re not waiting for him to finish the execution.

Exchange the code for the following:

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

And look at my answer about Asynchronous call with async and await. There’s a really cool example showing how it works and what happens when it’s poorly employed.

  • Thiago, sorry I didn’t understand very well, when I tried that way I got the error: Cannot convert from void to System.Action.

  • Because you should not create asymptomatic methods that have no return. Every asynchronous method must return Task - if it does not return any value - or Task<T> if it returns any value. See the answer Linkei on asynchronous calls, explain it right there.

  • Yes, I understand now, but with the Task.Run(() => ConnectServer()).Wait(); doesn’t work out, because when you click on connect all the flow hangs and waits for the connection to finish... I want you not to lock.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.