From now I'm a beginner in Async coding, I just can't see what I could do in this example.
I have two projects, one have the classes to communicate to a certain service, and the another one is the WinForms project.
So I have a reference in the WinForms from the other project that allows me to create instances of the Client object to use it like I want.
The problem is, because of that, I can't use System.Windows.Forms.MessageBox.
Then, I'd use the try...catch in the Form class, but... The problem now is that I can't get the exception, the system just don't grab it and continues to execute untill the app crash itself.
So, here's my little project with the class that wraps the logic to connect into the server.
(ps.: When I mean projects, I mean that I have a solution in Visual Studio 2013 with two projects, a Class Library and a Win Forms Application)
public class Client
{
public Client(string host, int port)
{
Host = host;
Porta = port;
Client = new TcpClient();
Connect();
}
public string Host { get; set; }
public int Port { get; set; }
public TcpClient Client { get; set; }
private async void Connect()
{
await Client.ConnectAsync(Host, Port);
}
}
And here's the other project with the main form.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
Client client = new Client("localhost", 8080);
}
catch (SocketException socketException)
{
MessageBox.Show(socketException.Message);
}
}
}
See Question&Answers more detail:os