Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a C# library thread safe for WPF animations

Tags:

c#

.net

wpf

I'm using the Artefact Animator library. This library is not thread-safe I've found.

Why does it need to be thread safe? My WPF application has multiple UI threads.

Is there a good trick to making this thread safe without re-coding the library? I've hacked it into submission by making multiple copies of the library and changing the library namespace for every thread I'm starting, but this is a poor solution because now I have multiple copies of my source code with tweaked using statements. Maybe there's some way to automate this or wrap the namespaces with reflection? I don't know.

For background on why I'm doing this: I have somewhere between 5 and 15k WPF image objects that I'm animating (on multiple monitors). The animations get choppy when they're all running on one thread. If someone has a better way to do this also, I'm open to solutions.


1 Answers

WPF requires that all windows/controls/dependency objects have thread affinity. So if you create a WPF window on a thread then all changes to that window must occur on the same thread in the future. As a result, virtually all WPF applications therefore have just a single user interface thread. Other threads might be used for background processing or other data processing activity but the feedback is then sent to the user interface thread for display.

I suspect your Artefact Animator library was written with this assumption in mind because that is how the majority of WPF apps are written. Converting the library requires you to understand its design and then correctly redesigning it to work as desired. This might be simple or near impossible depending on the library.

like image 67
Phil Wright Avatar answered Feb 21 '26 10:02

Phil Wright