i am using the code below to create a live tile, based on an UI element.
It renders the uiElement
on a WriteableBitmap
, saves the bitmap + returns
i get same exception when convert uielement to writeablebitmap in taskagent. just tried so many times.i found a soluction get be worked.
wbmp.SaveJpeg(stream, width, heigth, 0, 60);
you can change the quality to 60 when you save uielement to stream. it well reduce memory useage. you can try it.
The Problem is that rectangle.RenderTransform is an instance of an object and if you set writableBitmap to null the rectangle.RenderTransform Object is still alive and holds the rectangle in the memory... so the solution is to edit the code as follows:
private void CreateImage()
{
var rectangle = CreateRectangle();
var writeableBitmap = new WriteableBitmap(rectangle, rectangle.RenderTransform);
rectangle.RenderTransform = null; //and your memory would be happy ;)
rectangle = null;
writeableBitmap = null;
GC.Collect();
}
see the memory screenshots...
before:
after:
Try to put this part:
uiElement = null;
wbmp = null;
GC.Collect();
to finally clause;
Your finally in the try catch should be wbmp = null for a kick off.
And you are rendering it, which means you are attaching that object to an outside (the function) list. Therefore no amount of GC.Collect will actually collect it as it's still 'in play'.
Set the uielement source to null, that may get rid of the attached reference why the GC is ignoring it.
You can limit the size of writable bitmap image width X height to smaller size as you when increase its size it takes more memory so you can limit its initial size at first then save as jpeg with original tile size