Can FMX.Graphics.TBitmap.Canvas safely be created by threads?

  

I’m maintaining a Delphi 10.2.3 Isapi application that uses FMX.Graphics.TBitmap.
Multiple threads are creating their own private bitmap, draw on it, return the binary content to the webrequest handler, and free the bitmap.
While debugging access violations are occuring in this stack trace:

:760c4742 KERNELBASE.RaiseException + 0x62
System.DynArraySetLength(nil,$407163,16,$F)
System.DynArraySetLength($6113648,$5DDE84,1,$6B6FE78)
System.Generics.Collections.TListHelper.InternalSetCapacity(8514146)
System.Generics.Collections.TListHelper.InternalGrow(???)
System.Generics.Collections.TListHelper.InternalGrowCheck(???)
System.Generics.Collections.TListHelper.InternalAddManaged((no value))
System.Messaging.TMessageManager.SubscribeToMessage(???,(FMX.Canvas.D2D.TCanvasD2D.ContextLostHandler,$6122F70))
FMX.Canvas.D2D.TCanvasD2D.CreateFromBitmap(???,SystemDefault)
FMX.Graphics.TBitmap.GetCanvas
Unit1.TWorker.Execute

I suspect that this code in the FMX framework code is not threadsafe:

// FMX.Canvas.D2D.pas:
constructor TCanvasD2D.CreateFromBitmap(const ABitmap: TBitmap; const AQuality: TCanvasQuality);
begin
inherited;
FLastBrushTransform := TMatrix.Identity;
CreateResources;
FContextLostId := TMessageManager.DefaultManager.SubscribeToMessage(TContextLostMessage, ContextLostHandler);
end;

It is calling the singleton TMessageManager.DefaultManager and adding a handler to it’s internal dictionary, without any locking. That doesn’t look very threadsafe.
According to the documentation FMX bitmaps can be used in threads when using BeginScene and EndScene, which is fine.
But actually creating/destroying a FMX canvas does not seem to be threadsafe because of the subscribe/unsubscribe to the singleton default MessageManager? Is this assumption correct?

The strange thing is that it might only raise access violations when any code has been paused and resumed somewhere in the debugger via a breakpoint.
When the program is never paused by breakpoints it will run without problems.

Comments are closed.