如何从GUI文本框访问我的运行代码线程。 C#表格[关闭]

问题描述 投票:-1回答:1

我正在尝试访问该方法中的方法和变量,该方法也位于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 
}

谢谢你的回答。

c# winforms
1个回答
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的字段不受编译器优化的约束,这些优化假定由单个线程进行访问。这可确保始终在字段中显示最新值。

© www.soinside.com 2019 - 2024. All rights reserved.