How to access a non-static method from a thread in C#
I'm not sure if this is good programming etiquette, anyway I have a normal method in which I update certain bits of data and UI elements such as textblocks etc.
Anyway, I want to create a thread that every X amount of Seconds it runs the Update Method but I cannot access it because from what I understand a thread can only run static methods.
What is the best way around this?
T开发者_如何学Chanks,
mg.
from what I understand a thread can only run static methods.
This is simply not true. You can start a thread like this:
Thread thread = new Thread(() => { foo.bar(123, 456); });
thread.Start();
The method bar does not have to be static, but you do need to have a reference to an object to be able to call an instance method.
If you have a parameterless method you can also do this:
Thread thread = new Thread(bar);
You should note that you cannot modify the GUI from another thread than the main thread, so if all you want to do is update the GUI you shouldn't start a new thread. If you have a long running process and want to update the GUI occasionally to show progress without blocking the UI you can look at BackgroundWorker.
Alternatively you can update the GUI from a background thread using the Invoke pattern:
private void updateFoo()
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(() => { updateFoo(); }));
}
else
{
// Do the update.
}
}
See this related question: C#: Automating the InvokeRequired code pattern
If you want to update UI elements based on the progress of the thread, you should probably look into the BackgroundWorker class (http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)
精彩评论