0

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.

LionAM
  • 1,271
  • 10
  • 28
  • async/await doesnt help? – Ugur Aug 31 '21 at 10:11
  • My problem is not that I am waiting for the result but that the operation is very processor intensive, so if I'm starting a new task/thread on every change, these operations will sum up. – LionAM Aug 31 '21 at 10:18
  • 1
    RenderTargetBitmap has no API that supports cancellation, obviously. – BionicCode Aug 31 '21 at 10:23
  • 1
    Does this answer your question? [Asynchronously render a WPF visual to a bitmap](https://stackoverflow.com/questions/36402011/asynchronously-render-a-wpf-visual-to-a-bitmap) – Ugur Aug 31 '21 at 10:27
  • Looks promising, but I did not yet get it to work. It throws an InvalidOperationException when trying to render an UIElement that is not in the visual tree ("Not connected to a PresentationSource") – LionAM Aug 31 '21 at 14:58

1 Answers1

1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Ok. I think I will split the rendering into multiple parts and render them individually, if the time gets too long. – LionAM Sep 01 '21 at 06:57