C# Saving Panel as image at Multithread

纵然是瞬间 提交于 2019-12-11 15:13:06

问题


I don't have any problem saving panel as image with UI thread but i have only a black rectangle when i save this panel at another thread except UI thread :

using (Bitmap bmp = new Bitmap(panel1.Width, panel1.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
        {
            if (panel1.InvokeRequired)
            {
                panel1.BeginInvoke((MethodInvoker)delegate ()
                {
                    panel1.DrawToBitmap(bmp, new System.Drawing.Rectangle(Point.Empty, bmp.Size));

                });
                Bitmap bb = bmp.Clone(new System.Drawing.Rectangle(0, 0, 1016, 648), PixelFormat.Format24bppRgb);
                bb.Save(@"C:\sample.bmp", ImageFormat.Bmp);
            }
            else
            {
              panel1.DrawToBitmap(bmp, new System.Drawing.Rectangle(Point.Empty, bmp.Size));
              Bitmap bb = bmp.Clone(new System.Drawing.Rectangle(0, 0, 1016, 648), PixelFormat.Format24bppRgb);
              bb.Save(@"C:\sample.bmp", ImageFormat.Bmp);
            }

        }

This problem is related with locking mechanism? Or how can i solve this problem?

Thanks in advance.


回答1:


Universal answer (with explanation):

BeginInvoke is function that send a message 'this function should be executed in different thread' and then directly leaves to continue execution in current thread.

The function is executed at a later time, when the target thread has 'free time' (messages posted before are processed).

When you need the result of the function, use Invoke. The Invoke function is 'slower', or better to say it blocks current thread until the executed function finishes. (I newer really tested this in C#, but it s possible, that the Invoke function is prioritized; e.g. when you call BeginInvoke and directly after it Invoke to the same thread, the function from Invoke will probably be executed before the function from BeginInvoke.)

Use this alternative when you need the function to be executed before the next instruction are processed (when you need the result of the invoked function).

Simple (tl;dr): When you need to need to only set a value (e.g. set text of edit box), use BeginInvoke, but when you need a result (e.g. get text from edit box) use always Invoke.

In your case you need the result (bitmap to be drawn) therefore you need to wait for the function to end. (There are also other possible options, but in this case the simple way is the better way.)



来源:https://stackoverflow.com/questions/49433837/c-sharp-saving-panel-as-image-at-multithread

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