我认为我已经发现了RescueAttribute失效的情况。或者我可能没有正确使用协程。
我的ViewModel如下:
[Rescue("Rescue")]
class MyViewModel
{
//... left out some bus-logic code here ...
public void Login()
{
yield return Show.Busy();
//the following line will also cause the problem, just like AsyncResult
//yield return Show.MessageBox("Test");
yield return new AsyncResult(() => _server.Login());
//throw new Exception("Aww, snap!");
yield return Show.NotBusy();
}
public void Rescue(Exception exc)
{
//Show a messagebox or something
}
}
AsyncResult的实现方式如下:
using Exec = Caliburn.PresentationFramework.Invocation.Execute;
public class AsyncResult : IResult
{
private readonly Action _function;
public AsyncResult(Action function)
{
_function = function;
}
public void Execute(ResultExecutionContext context)
{
Exec.OnBackgroundThread(delegate
{
try
{
_function();
}
catch (Exception exc)
{
Exec.OnUIThread(() => Completed(this, new ResultCompletionEventArgs { Error = exc, WasCancelled = true }));
return;
}
Exec.OnUIThread(() => Completed(this, new ResultCompletionEventArgs()));
});
}
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
如果我取消上述ViewModel中的异常注释,Rescue就无法处理异常。
这是Caliburn的一个bug吗,还是AsyncResult实现有误?
如果在yield返回AsyncResult之前抛出异常,则Rescue仍然可以正常工作。而且如果异常是在异步线程上抛出的,Rescue也可以正常工作!
编辑:您也可以使用Show.MessageBox代替AsyncResult来重现相同的问题。