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

感情迁移 提交于 2019-12-04 05:25:28

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.

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