更新一个线程中的文本

时间:2017-06-19 08:36:04

标签: c# multithreading forms

我有一个问题,我需要更新线程中运行的表单中的文本,但无法正常工作,这是我的现有代码:

public partial class Class1: Form
{
    LoadText = loadText;
    ResourceName = resourceName;

    static private void ShowForm()
    {
        LoadForm = new Class1(LoadText, ResourceName);
        Application.Run(LoadForm);
    }

    static public void ShowLoadScreen(string sText, string sResource)
    {
        LoadText = sText;
        ResourceName = sResource;

        Thread thread = new Thread(new ThreadStart(Class1.ShowForm));
        thread.IsBackground = true;
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }
}

现在我需要在新启动的表单下更改文本框中的文本,这需要从理论上的“Class2”执行:

class Class2
{
   public void UpdateThreadFormTextbox
   {
      Class1.ShowLoadScreen("text", "text");
      //Change textbox in the thread instance of Class1 form
   }
}

我已经研究过使用'Invoke',但是我无法使用Class2中的那个,是否有一个解决方案可以让我从Class2更新Class1线程实例中的文本?

2 个答案:

答案 0 :(得分:2)

只需使用Class1中的Invoke:

public partial class Class1: Form
{
    private static Class1 LoadForm;

    static private void ShowForm()
    {
        LoadForm = new Class1(LoadText, ResourceName);
        Application.Run(LoadForm);
    }

    static public void ShowLoadScreen(string sText, string sResource)
    {
        LoadText = sText;
        ResourceName = sResource;

        Thread thread = new Thread(new ThreadStart(Class1.ShowForm));
        thread.IsBackground = true;
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }

    public static void SetText(string text)
    {
        Class1.LoadForm.textBox1.Invoke(new Action(() => Class1.LoadForm.textBox1.Text = text));
    }
}

然后使用Class2中的那个方法:

class Class2
{
   public void UpdateThreadFormTextbox
   {
      Class1.ShowLoadScreen("text", "text");
      Class1.SetText("TEXT");
   }
}

答案 1 :(得分:1)

您也可以通过将文本框的实例传递到UpdateThreadFormTextBox方法并通过Invoke

调用Class2来实现此目的。
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Create instance of Class2
        Class2 secondClass = new Class2();
        // Create a new thread, call 'UpdateThreadFormTextbox' 
        // and pass in the instance to our textBox1, start thread
        new Thread(() => secondClass.UpdateThreadFormTextbox(textBox1)).Start();
    }
}

public class Class2
{
    public void UpdateThreadFormTextbox(TextBox textBox)
    {
        textBox.Invoke(new Action(() => textBox.Text = "Set from another Thread"));
    }
}