C#线程 - 父访问问题

时间:2009-08-21 12:10:35

标签: c# winforms inheritance multithreading parent-child

我的目标是在函数“Dummy”中我可以更改控件,如标签等线程正在启​​动的方式。如何做...请不要提出完全不同的策略或制作工人class etc ...如果可以的话,修改这个

        Thread pt= new Thread(new ParameterizedThreadStart(Dummy2));


        private void button1_Click(object sender, EventArgs e)
        {                    
            pt = new Thread(new ParameterizedThreadStart(Dummy2));
            pt.IsBackground = true;
            pt.Start( this );
        }


        public static void Dummy(........)
        {
           /*                
           what i want to do here is to access the controls on my form form where the
           tread was initiated and change them directly
           */ 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (t.IsAlive)
                label1.Text = "Running";
            else
                label1.Text = "Dead";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            pt.Abort();
        }


    }
}

我的计划是我可以在“假人”功能

中做到这一点
Dummy( object p)
{
  p.label1.Text = " New Text " ;
}

3 个答案:

答案 0 :(得分:4)

您可以这样做,假设您使用t.Start(...)方法将表单实例传递给线程方法:

private void Form_Shown(object sender)
{
    Thread t = new Thread(new ParameterizedThreadStart(Dummy));
    t.Start(this);
}

....


private static void Dummy(object state)
{
    MyForm f = (MyForm)state;

    f.Invoke((MethodInvoker)delegate()
    {
        f.label1.Text = " New Text ";
    });
}

修改
为清晰起见,添加了线程开始代码。

答案 1 :(得分:3)

你不能这样做。您只能在创建它的同一个线程上访问UI控件。

请参阅System.Windows.Forms.Control.Invoke MethodControl.InvokeRequired属性。

答案 2 :(得分:2)

可以使用这样的东西:

private void UpdateText(string text)
{
    // Check for cross thread violation, and deal with it if necessary
    if (InvokeRequired)
    {
        Invoke(new Action<string>(UpdateText), new[] {text});
        return;
    }

    // What the update of the UI
    label.Text = text;
}

public static void Dummy(........)
{
   UpdateText("New text");
}