c#从UI线程静态更新控件

时间:2018-05-28 08:41:50

标签: c# multithreading user-interface static

例外:

Controls created on one thread cannot be parented to a control on a different thread.

This thread很好地解释了如何在类的实例上执行它,(使用此关键字)静态不引用实例,所以我运气不好。

调用函数不是静态的类,并且正在调用此函数......

DrawPlane.drawPlane(ref pnl);

同样在通话类中,我使用这个顽皮的属性来尝试减轻非法的跨线程......

CheckForIllegalCrossThreadCalls = false;

全班:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Skork.ui {
class DrawPlane {

    private static int numX;
    private static int numY;
    private static BackgroundWorker bg;

    static DrawPlane() {
        numX = 0;
        numY = 0;
        bg = new BackgroundWorker();

    }      

    public static void drawPlane(ref Panel plane) {           
        bg.DoWork += Bg_DoWork;
        bg.RunWorkerAsync(plane);
    }

    private static void Bg_DoWork(object sender, DoWorkEventArgs e) {
        Panel plane = new Panel();

        if (e.Argument is Panel) {
            plane = (Panel) e.Argument;
        } else {
            throw new Exception("Object is not a panel!!" +
                e.Argument.ToString());
        }


        plane.Controls.Clear();
        numX = 0;
        numY = 0;

        Random rnd = new Random();
        Size sz = plane.Size;
        Point temp = new Point(0, 0);
        const int sizeUnit = 4; // 4 pixels wide
        bg.DoWork += Bg_DoWork; // add event
        int x = 0;

        for (int y = 0; y < sz.Height; y += sizeUnit * sizeUnit) {
            temp.X = 0;
            numY++;

            for (x = 0; x < sz.Width; x += sizeUnit * (sizeUnit / 2)) {

                if (x + temp.X < sz.Width) {
                    PictureBox unit = new PictureBox();
                    rnd = new Random(rnd.Next());

                    unit.Size = new Size(sizeUnit * sizeUnit, sizeUnit * sizeUnit);
                    unit.Location = new Point(x + temp.X, y + temp.Y);
                    unit.BackColor = Color.FromArgb(255, rnd.Next(255),
                        rnd.Next(255), rnd.Next(255));
                    unit.Click += Unit_Click;
                    plane.Controls.Add(unit);

                    temp.X += sizeUnit * 2;
                    temp.Y = 0;
                    numX++;

                } else {
                    continue;
               }
            }
        }
        numX = numX / numY; // determine number of boxes on X-axis
    }

    private static void Unit_Click(object sender, EventArgs e) {
        if (sender is PictureBox) {
            PictureBox p = (PictureBox)sender;
            MessageBox.Show(p.Location.ToString() + " = Number in x-axis " + numX + " - number in y-axis " + numY);
            return;
        }            
        throw new Exception("Not a picturebox for some reason. - " + sender.ToString());
    }        
}

}

0 个答案:

没有答案
相关问题