C# 如何在Page.RegisterAsyncTask方法中使用try-catch块

C# 如何在Page.RegisterAsyncTask方法中使用try-catch块,c#,asp.net,.net,asynchronous,C#,Asp.net,.net,Asynchronous,我有以下代码来运行一些异步调用。我试图捕获数据库超时异常并显示一些用户友好的消息 但将try,catch块放入endInvoke,操作不会执行。我正在使用ASP.NET4.0和C#4.0 然后 如何在Page.RegisterAsyncTask方法中使用try-catch块 注意:我想通过db超时和异步操作防止对象引用错误您说myObj.Property导致NullReferenceException。那么,为什么您希望用catch(MyTimeoutException)捕获它呢 您正在使用AP

我有以下代码来运行一些异步调用。我试图捕获数据库超时异常并显示一些用户友好的消息

但将
try,catch块放入endInvoke,操作不会执行。我正在使用ASP.NET4.0和C#4.0

然后

如何在Page.RegisterAsyncTask方法中使用try-catch块


注意:我想通过db超时和异步操作防止对象引用错误

您说
myObj.Property
导致
NullReferenceException
。那么,为什么您希望用
catch(MyTimeoutException)
捕获它呢


您正在使用APM模式。这需要调用
EndXxx
方法来获取操作结果、获取任何异常并可能释放资源。调用
EndXxx
方法。

你说得对。我能够在原始方法中捕获异常。但是,在访问
endXXX
之前,我需要检查空值。那么为什么不这样做呢?为什么不尝试捕获多次(既捕获(MyTimeOutException)又捕获(NullReferenceException)?不捕获NRE。
如果(myObj==null)返回;
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(beginMyMethod)
      , new EndEventHandler(endMyMethod), new EndEventHandler(timeout => { })
      , true, true));
Page.ExecuteRegisteredAsyncTasks();
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
 }
}