C # WinForms: drawing with one or more additional threads. How?

In case I have a large drawing with all kinds of geometric shapes (lines, rectangles, circles, etc), it will take a lot of time for the stream to draw everything. But in real life, one building was built by more than one worker. Therefore, if the drawing is a building and the flows are builders, it will be drawn much faster. But I want to know how.

Can you tell me how to do this? Is this possible (although I already asked, and the answer was "Yes")? Should I use it? What are the risks?

If there are questions that I missed, let me know about them and answer them.

Thanks!

+6
source share
3 answers

Assuming you are using GDI + and System.Drawing.Graphics objects to render your graphics (rectangles, circles, etc.) to the surface of the background image (e.g. System.Drawing.Bitmap Object): members of the System.Drawing.Graphics object instance System.Drawing.Graphics that you would need to use is not thread safe . See MSDN documentation here

Given this, I would not use more than one builder stream to render your graphics.

Instead, my recommendation would be to make your entire drawing a System.Drawing.Bitmap object in the background thread single , rather than in case it is possible. You can use the status bar or other indicator so that the user knows that your program is running in the background.

+5
source

WinForms objects have strong thread similarity, which makes it impossible to manipulate a form or control from a thread other than the one who created it.

However, it's worth checking if this statement is true for Graphics .

From System.Drawing.Graphics class docs:

All public static (Shared in Visual Basic) members of this type are safe thread. Any instance members are not guaranteed to be safe threads.

Doesn't smell good: all drawing methods are instance members. You cannot distribute operations on a Graphics object across multiple threads.

+1
source

As a simple example, you can use threads to perform several tasks using the ThreadStart delegation method, it will look something like this:

  Thread t = new Thread(new ThreadStart(MethodToExecuteOnSecondThread)); t.Start(); while (!t.IsAlive) { //do something to show we're working perhaps? UpdateMyGuiWithALoadingBar(); } 

You are the second thread, then it shuts down and executes the ThreadStart () delegation method, while the main thread remains responsive.

0
source

Source: https://habr.com/ru/post/898149/


All Articles