简体   繁体   中英

C# Handling Response Exception within ContinueWith Task (WinForms)

I hope everyone's doing well.

So we were tasked with using a method of multi-threading to run a GetResponse method.

WebResponse response = await Task.Run(() => request.GetResponse())

This works perfectly with the rest of my program.

Now , the issue takes place when I type a web address which is non existent and an exception occurs.

I've been trying to figure out a good way to catch this exception and add it to the label, but I have been unable to do so.

WebResponse response = await Task.Run(() => request.GetResponse())
            .ContinueWith(
            ex =>
            {
                if (ex.Exception != null)
                    ex.Exception.Handle(x =>
                    {
                        Label1.Text = (x.Response as HttpWebResponse).StatusCode;
                        return true;
                    });
            });

In this code snippet, I can't figure out how to catch the exception that is thrown. (Exception could be 404 error, or other)

Any help would be greatly appreciated. Thank You!

Get your exceptions like below

 List<Exception> Exceptions = ex.Exception.InnerExceptions.ToList();

and loop through them to find the task exceptions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM