wpfcancellationrendertargetbitmap

Cancel long running render operation in WPF


Is there any way to cancel a possibly long running render operation in WPF? In my case, I want to render a complex control (in a non-UI-thread) to a bitmap.

var bitmap = new RenderTargetBitmap((int)RenderSize.Width, (int)RenderSize.Height, 96, 96, PixelFormats.Default);
bitmap.Render(visual);    //May take several seconds, but the result may be obsolete

If the size of the target or some other properties change, the bitmap being currently drawn is obsolete - therefore I would like to stop the rendering as fast as possible.


Solution

  • Is there any way to cancel a possibly long running render operation in WPF?

    Short answer: No.

    You can't cancel an API that doesn't support cancellation.

    A synchronous API such as RenderTargetBitmap.Render doesn't return until it has either finished or thrown an exception. You cannot "cancel" it after you have called it I am afraid.

    Depending on how and where your bitmap is used, you may consider rendering it on a background thread.