Handle a exception that happens in a asynchronous

2019-09-20 11:20发布

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);
        }
    }
}

2条回答
别忘想泡老子
2楼-- · 2019-09-20 11:42

In the past, I always use a generic object that holds whatever I want to get from the client to the server, but also has a violations list property and a boolean success property.

If I get an exception on the server, I set success equals false and put the error message in the violations list. If you want more details, put the exception itself into the list. Then on the client I check if my call was successful. If so, great, grab the data I need. Otherwise print the errors in the violations list.

查看更多
放荡不羁爱自由
3楼-- · 2019-09-20 11:47

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);
    }
}
查看更多
登录 后发表回答