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();
}
Thiago, sorry I didn’t understand very well, when I tried that way I got the error:
Cannot convert from void to System.Action
.– Raizant
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.
– Thiago Lunardi
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.– Raizant