System barely usable: WindowServer & CoreGraphics API

I work on a macOS app which uses the CoreGraphics APIs to retrieve the whole screen as an image, or the various windows of an application. This is for a screen sharing feature. Notably, we use CGWindowListCreateImageFromArray. We occasionally run into an issue where Apple's WindowServer process starts to consume a lot of CPU (close to 100%) and the whole system becomes incredibly sluggish, almost unusable.


The problem persists even when you stop the screen sharing and we aren't calling the APIs anymore, until you terminate the app.


Has anyone who has worked with the CoreGraphics APIs, have knowledge of how they connect with the WindowServer process to give some insight into what we might be doing that perturbs the WindowServer in these cases?


A spindump of the system sometimes shows that indeed our app and others are waiting on the WindowServer, which is taking up almost all the time of the spindump in its main thread. However, other times, it's not quite as clear cut. Seems like some kind of "soft" deadlock, since the WindowServer isn't completely frozen (since the UI is still somewhat accessible).


Any help is much appreciated! Thanks.