Handle a exception that happens in a asynchronous method in C#

纵饮孤独 提交于 2019-12-25 18:17:51

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/22569243/handle-a-exception-that-happens-in-a-asynchronous-method-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!