C# WinForms: Drawing with one or more additional threads. How?
In case I have a big drawing with all kinds of geometric forms (lines, rectangles, circles, e.t.c.) it takes a lot of time for the thread to draw everything. But in real life, one building is built by more than one workers. So if the drawing is the building and the threads are the builders, it will get drawn a lot faster. But I want to know how.
Can you tell me how? Is it even possible (though I have already asked and the answer was "Yes")? Is it worth it to be used? What are the risks?
If there are questions that I have missed开发者_如何学运维, please tell me about them and answer them.
Thanks!
Assuming you are using GDI+ and the System.Drawing.Graphics
object to render your graphics (rectangles, circles, etc.) to a background drawing surface (e.g. System.Drawing.Bitmap
Object): Instance members of the System.Drawing.Graphics
object that you would need to use are not thread safe. See MSDN documentation here
Given this, I would not use more than one "builder" thread to render your graphics.
Instead, my recommendation would be to do all of your drawing to a System.Drawing.Bitmap
object in a single background thread rather than multiple background threads if possible. You can use a status bar or other indicator to let the user know that your program is working in the background.
WinForms objects have strong thread affinity, making it impossible to manipulate a form or control from a thread different than the one who created it.
That said, it's worth investigating if this assertion is true for Graphics
as well.
From the System.Drawing.Graphics class docs:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Doesn't smell good: All drawing methods are instance members. You can't spread operations on the Graphics
object accross several threads.
As a simple example you can use threads to do multiple tasks using the ThreadStart delegate method, it would look something along these lines:
Thread t = new Thread(new ThreadStart(MethodToExecuteOnSecondThread));
t.Start();
while (!t.IsAlive)
{
//do something to show we're working perhaps?
UpdateMyGuiWithALoadingBar();
}
You're second thread then goes off and executes the ThreadStart() delegate method while you main thread stays responsive.
精彩评论