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

青春壹個敷衍的年華 提交于 2019-12-21 12:28:46

问题


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!


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7570585/c-sharp-winforms-drawing-with-one-or-more-additional-threads-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!