简体   繁体   中英

How to use try catch block in Page.RegisterAsyncTask methods

I have the following code to run some asynchronous call. I am trying to capture the database timeout exception and show some user friendly message.

But putting try, catch block in endInvoke, action does not getting executed. I am using ASP.Net 4.0 & C# 4.0

Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(beginMyMethod)
      , new EndEventHandler(endMyMethod), new EndEventHandler(timeout => { })
      , true, true));
Page.ExecuteRegisteredAsyncTasks();

Then

IAsyncResult beginMyMethod(object sender, EventArgs e, AsyncCallback cb, object state)
{
        Action r = myMethod;
        return r.BeginInvoke(cb, state);
}


void endMyMethod(IAsyncResult asyncResult)
{
  try{
   myObj.Property // gives object reference error, as it was not set, since DB timeout

  }
  catch(MyTimeoutException ex){
   //it is not getting called
  }
}


private void MyMethod()
{
 try{
   MyObject myObj= //making a database call causes DB time out error
 }
 catch(MyTimeoutException ex){
    //it is getting called
 }
}

How to use try catch block in Page.RegisterAsyncTask methods

Note: I want to prevent object reference error with db time out and async operation

You say that myObj.Property results in a NullReferenceException . Why do you expect to catch it with a catch (MyTimeoutException) , then?

You are using the APM pattern. This requires calling the EndXxx method to get the result of the operation, get any exceptions and potentially release resources. Call the EndXxx method.

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