Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatcher.Invoke does not catch exception

I have a code below to get a response from HTTP GET:

private void ResponseReady(IAsyncResult aResult)
{
    HttpWebRequest request = aResult.AsyncState as HttpWebRequest;

    try
    {
        this.Dispatcher.BeginInvoke(delegate()
        {
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(aResult);

The problem when there is no connection, it will stop at the response row. It doesn't catch the exception. Is it because of the Dispatcher.Invoke?

like image 525
Alvin Avatar asked Feb 17 '23 16:02

Alvin


2 Answers

Your exception isn't caught because the call to BeginInvoke does not execute the code in your delegate, it queues it to be executed on a ThreadPool Thread. When your exception does occur there is no exception handling in place. Did you mean to use Invoke or BeginInvoke here? Either way putting the exception handling in the delegate should take care of your problems.

like image 160
HasaniH Avatar answered Feb 27 '23 06:02

HasaniH


The code inside BeginInvoke delegate is executed in a different thread, you need to create a separate try/catch there.

like image 28
user626528 Avatar answered Feb 27 '23 06:02

user626528