我正在为Windows Phone 8.1(Silverlight)开发C#应用程序。最近我遇到了与应用程序入睡和故事板有关的问题。Catch不执行其代码
构造变为如下:
class X : DependencyObject
{
public static readonly DependencyProperty vProperty =
DependencyProperty.Register("v", typeof(double), typeof(X), new PropertyMetadata(0.0));
public double v
{
get
{
return (double)GetValue(vProperty);
}
set
{
SetValue(vProperty, value);
}
}
private Storyboard _storyboard;
void Prepare()
{
_storyboard = new Storyboard();
var animation= new DoubleAnimation
{
From = 0,
To = 1,
BeginTime = 0,
Duration = 0,
};
_storyboard.Children.Add(animation);
Storyboard.SetTarget(animation, this);
Storyboard.SetTargetProperty(animation, vProperty);
}
void Go()
{
_storyboard.Begin();
}
}
有从_storyboard.Begin()的内部抛出一个NullReferenceException如果应用设备被置于背景“准备”和“去”(约10%的再现速率之间)。当然,它最终会崩溃。
我无法确定问题的来源,因为我需要quickfix,因此我决定在这种罕见的情况下发现这个NullRefereneceException。这是真正的问题开始的地方。我已经改变了“去”实施:
public void Go()
{
Debug.WriteLine("BreakPoint 1");
try
{
_storyboard.Begin();
}
catch (NullReferenceException)
{
Debug.WriteLine("BreakPoint 2");
}
}
之后崩溃是不可复制的所有,但问题是,“断点2”从不打(在输出中没有打印其一)。 “BreakPoint 1”通常也会被打印和打印。将NullReferenceException更改为其他异常类型(不是父类型的c)会导致崩溃重新出现。
那么......这里发生了什么事?这崩溃缓存或不?这是什么奇怪的行为?假设它能按预期工作是否安全?
附加问题:也许你知道为什么原始代码崩溃的第一个地方?
编辑: 结束TargetInvocationExceptions的internalException的堆栈跟踪看起来如下:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.Storyboard_Begin(Storyboard storyboard)
at System.Windows.Media.Animation.Storyboard.Begin()
at X.Go()
那么程序仍然崩溃或没有?如果你有它捕获一个通用的'例外'会发生什么? – user1666620
它没有崩溃,但它看起来像捕获内的代码不会执行。任何NullRefrenceException父类的异常类型都会修复崩溃。任何其他异常类型都不能修复崩溃。 – Yester
如果你得到一个'TargetInvocationException',那么这就是你需要捕获的。 'InnerException'属性可能是你的'NullReferenceException',但你不能理解(除非你使用C#6.0,你可以这样做:'catch(TargetInvocationException ex)when(ex.InnerException是NullReferenceException)') 。 –