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

时间:2014-09-01 11:31:56

标签: c# asp.net .net asynchronous

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

但是try, catch block in endInvoke, action没有被执行。我正在使用ASP.Net 4.0& C#4.0

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

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

注意: 我希望通过db time out和async operation阻止对象引用错误

1 个答案:

答案 0 :(得分:1)

您说myObj.Property会产生NullReferenceException。为什么你期望用catch (MyTimeoutException)来捕捉它呢?

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

相关问题