Hello
Why I haven’t access to my private control on form (e.g. ListBox) from a static method?
How to update control in this case?
EDIT 1.
my code:
ThreadStart thrSt = new ThreadStart(GetConnected);
Thread thr = new Thread(thrSt);
thr.Start();
and
static void GetConnected()
{
//update my ListBox
}
So it must be void, without param and be static, right?
EDIT 2.
If someone need solution in WPF then should try this:
private void GetConnected()
{
myListBox.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
myListBox.Items.Add("something");
}
)
);
}
Static methods cannot access instance state (such as a non-static control). Either remove
staticfrom the method declaration, or pass a reference to the control as argument to the method:…and call it like so:
Update
There are different ways to do asynchronous things in the UI (now assuming winforms). I would recommend you to look into using
BackgroundWorker(search here on SO; plenty of examples). If you really want to do it by creating threads on your own, here is one way to do that:…and to call it:
You can also use the thread pool (preferred over creating your own threads, given that you don’t expect them to run for very long):