1

I have some rendering code, which relies on DrawingContext.PushClip and the corresponding Pop method.

protected override void OnRender(DrawingContext drawingContext)
{
    drawingContext.PushClip(whatever);
    OnRenderInternal(...);
    drawingContext.Pop();
}
  • Now, let's assume that something really bad happens in the OnRenderInternal method and it throws an exception (in this case Pop will never get called). Would this break the entire rendering process or the drawing context will revert itself to some "safe" state before performing other operations (and no clipping will occure for other renderable items)?

  • Basically, should I always care about reverting the drawing context to its initial state when performing rendering operations?

  • I realize that in this simple case I can avoid troubles by using a try-finally statement, but what would happen if I forget to preserve the correct Push / Pop stack?

4

2 回答 2

2

I think there is typically no need to revert the DrawingContext to its initial state, for the simple reason that you get a new DrawingContext on every call to OnRender. The whole drawing is re-created every time OnRender is called and it doesn't matter in which state you leave the DrawingContext.

There is however an exception. A derived UIElement may also override OnRender and may first call base.OnRender() before performing its own rendering code. In this scenario the derived UIElement would get the "corrupted" DrawingContext from the base class' OnRender method.

So unless you can make sure that your UIElement can't be derived from, it looks like a good idea not to leave the DrawingContext in an undefined, "corrupted" state.

于 2012-10-12T22:50:52.660 回答
1

You could do:

protected override void OnRender(DrawingContext drawingContext)
{
    try
    {
        drawingContext.PushClip(whatever);
        OnRenderInternal(...);        
    }
    finally
    {
        drawingContext.Pop();
    }
}
于 2012-10-08T13:42:38.043 回答