c#winforms来自Warraper的交叉线程更新GUI

时间:2015-06-12 11:49:19

标签: c# winforms

我有两个类(Data_Reader和Display_Data)和一个GUI_Form 我想要的是显示GUI_Form上存在的Textbox上的Data_Reader类的读取数据,以便在我写入Display_Data类时包装它。
但我得到了以下例外:

  

跨线程操作无效:控制' textBox1'从在

上创建的线程以外的线程访问

有谁知道如何解决这个问题? 我只想更新GUI窗体上的读取数据值。

//    Gui Form
//    ============
public partial class GUI_Form: Form
{
}
//    ==============
//    Display Data Class
//    ===========
public static class Display_Data
{
    public delegate void MyDelegate(Label myControl, string myArg2);
    public static void DelegateMethod(Label myControl, string myCaption)
        {
            myControl.Text = myCaption;
        } 
}

//=========================
//  Reader Class
//=========================
public void Data_Reader
{
    string Data_Received_text="Test";
    private System.ComponentModel.ISynchronizeInvoke _syn;
    Meter_Data_Class.packets_received_counter_status_display++;
    //it will call the display_Data class delegate method to update textbox on gui
    syn.BeginInvoke(new
                  Display_Data.MyDelegate(Display_Data.DelegateMethod),Data_Received_text);

}

2 个答案:

答案 0 :(得分:0)

使用textBox1.BeginInvoke()来调用委托。

答案 1 :(得分:0)

您不能直接使用不是UI线程的线程的UI控件的方法或属性。 这就是你得到那个例外的原因。 为了克服这个障碍,您需要从将为您进行UI更改的不同线程调用委托。 Control命名空间中的System.Windows.Forms类包含一个名为InvokeRequired的属性,它告诉您当前线程是UI线程还是其他线程。 如果是UI线程,您可以使用control的属性和方法。 如果它不是UI线程,则必须调用delegate来使用control的属性和方法。这是一个简单的方法,它基于您发布的代码中的现有委托:

public static void DelegateMethod(Label myControl, string myCaption)
    {
    // Calling from another thread? -> Use delegate
    if (myControl.InvokeRequired) {
        MyDelegate d = new MyDelegate(DelegateMethod);
        // Execute delegate in the UI thread, pass args as an array
        this.Invoke(d, new object[] {
            myControl,
            myCaption
        });
    // Same thread, assign string to the textbox
    } else {
        myControl.Text = myCaption;
    }
}