Loading Resource in Worker Thread Really

Hello guys,

I want to implement a loading screen for my game. Resources such as texture should be loaded without blocking the main thread to deal with Monogame APIs. How can I make resource loading in a worker thread? It is sufficient if the method only works on Windows DirectX platforms. I welcome such a method rather than being dragged down by the circumstances of other platforms.

I know the usual answer for the situation is processing the resource loading queue in the remaining time of Draw method until the next frame. But loading each resource may take more time than the remaining time. It causes frame rate drop. Therefore I hope other worker threads to load resources than the main thread.
I read a source code of ContentManager and I found it looks thread-safe, but the Microsoft document says ID3D11DeviceContext::UpdateSubresource is not thread-safe so that Texture2DReader.Read which calls ID3D11DeviceContext::UpdateSubresource is also not thread-safe. When I tried ignoring this and creating and executing code to load textures in a worker thread, the program did not stall or fail to use the textures that were supposed to be loaded. However, since the code is not thread-safe, this is just a coincidence. Therefore, simply calling ContentManager.Load<Texture2D> method in the worker thread is not an appropriate approach.

I use coroutines to do this sort of thing. I put a package up on nuget if you want to try that, search for Monogame.Randochaos and it will list all my current packages.

I still need to write examples on the Git repo for them.

There’s nothing to worry about. If you look at SetData, the line above `UpdateSubresource locks
the content, and I ensure you this is true throughout the codebase.

However if you plan to port to the other GL based platforms then you’d better stay on the main thread for content loading. The openGL/GLES platforms dispatch every call to the main thread and your working thread is stalled until the next frame.

1 Like

Thank you both for your answers.

I must have missed the lock. I see that we are using a common d3dContext with a lock, so any thread can load the texture.
There looks to be not such a lock in the code to load effects. So the effects must be loaded in the main thread?