如何从GUI文本框访问我的运行代码线程。 C#表单

时间:2018-03-01 02:47:55

标签: c# winforms

我正在尝试访问该方法中的方法和变量,该方法也位于Windows窗体中GUI文本框的单独线程中。 人们遇到的每一个问题都是如何通过从一个与我试图做的相反的单独线程访问GUI来反过来。

public ClientWindow()
{
    InitializeComponent();
    var ItemThread = new Thread(new ThreadStart(ItemRun));
    ItemThread.Start();
}
public void ItemRun()
{    //..
}
public void Return(object sender, KeyEventArgs e)
{        //need to access a variable in ItemRun() from here 
}

感谢您的回答。

1 个答案:

答案 0 :(得分:1)

您只需要创建 Variable / s Global ,如果您需要线程安全,则需要使用某种锁定机制

// create global variable
private volatile int somevar;

// create a sync object to lock
private int _sync = new object();

...

public void ItemRun()
{   
    // make sure you lock it 
    // if there might be race conditions or you need thread safety
    lock(_sync)
    {
       // update your global variable
       somevar = 3;
    }
}
public void Return(object sender, KeyEventArgs e)
{       
    // lock it again if you need to deal with race conditions
    // or thread safty
    lock(_sync)
    {
       Debug.WriteLine(somevar);
    }
}

<强>更新

volatile (C# Reference)

  

volatile关键字表示字段可能被修改   多个线程同时执行。是的领域   声明的volatile不受编译器优化的限制   假设由单个线程访问。这确保了最多   字段中始终存在最新值。