Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

Avoid async void. You cannot catch exceptions thrown from async void methods.

public async Task ConnectAsync()
{
    await Client.ConnectAsync(Host, Port);
}

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        Client client = new Client("localhost", 8080);
        await client.ConnectAsync();
    }
    catch (SocketException socketException)
    {
        MessageBox.Show(socketException.Message);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...