[Mono-winforms-list] Is System.Drawing (libgdiplus) thread-safe?

Alex Shulgin alexander.shulgin at yessoftware.com
Wed Oct 28 13:37:46 EDT 2009


Hi all,

Is System.Drawing by any means thread-safe?

Can I create some threads, create a Graphics object in each of them and 
then work with it from within that thread?  Is this supposed to work or 
am I doing something really stupid here?

I ask because I've noticed random crashes in a WinForms app on OS X (but 
it happens on Linux too).  Most of the time it crashes in 
System.Drawing.Graphics' DrawString or MeasureString methods and seems 
to occur then a background worker thread is working in parallel with UI 
thread.

I've tried to do a stress-test of System.Drawing in a sample 
multi-threaded program.  See attached `test-multi-threaded-drawing.cs'.

On my Linux box it crashes all the time.  I get a wide variety of errors 
from gdb stacktraces with SIGSEGV or SIGABRT in the end, to SIGILL with 
.Net stack trace.

Uncommenting these lock {} lines in the ThreadProc helps, but not an 
option for my real app, as there's simply no single place a lock could 
be added.

I've also tried writing some code in plain C which links to libgdiplus 
directly: see `threads-gdiplus.c'.  It happily crashes just like the C# 
version.

My tests show that even using unsynchronized GdipGetImageGraphicsContext 
/ GdipDeleteGraphics (no fonts stuff touched) can easily lead to crashes.

 From what I've seen, cairo seems to be thread-safe: see attached[1] 
`cairo-multi-thread-text.c'.

Also, there's a few locking used around thread-unsafe fontconfig calls 
in libgdiplus itself.  I didn't examined the whole code, so there's 
possibly other places in it missing locking primitives.

I would appreciate any help on this subject!

--
Regards,
Alex
[1] originally found in the cairo bugzilla for a few-years-old bug; my 
sligthly enhanced version
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test-multi-threaded-drawing.cs
Type: text/x-csharp
Size: 2228 bytes
Desc: not available
Url : http://lists.ximian.com/pipermail/mono-winforms-list/attachments/20091028/ab5dd755/attachment-0003.bin 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cairo-multi-thread-text.c
Type: text/x-csrc
Size: 2638 bytes
Desc: not available
Url : http://lists.ximian.com/pipermail/mono-winforms-list/attachments/20091028/ab5dd755/attachment-0004.bin 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: threads-gdiplus.c
Type: text/x-csrc
Size: 3003 bytes
Desc: not available
Url : http://lists.ximian.com/pipermail/mono-winforms-list/attachments/20091028/ab5dd755/attachment-0005.bin 


More information about the Mono-winforms-list mailing list