Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[C#.NET] Multi-threading: Updating Non-Static Objects from Different Thread

Recommended Posts



// Create the delegate that will do the referencing.
delegate void UpdateLabelDelegate(string parameters);

// Define our Method. You can use any parameters you want, just make sure that the delegate and Invoke match.
public void AddMsg(string parameters)
// If we need to invoke
if (InvokeRequired)
// Then let's invoke and return. (After the invoke, we should NOT try to call this method as normal.)
Invoke(new UpdateLabelDelegate(AddMsg), parameters);

// Otherwise, no invoke was required. Continue as normal. Put your code after this.
So essentially, when you try to do something like modify a GUI element (Rich Text Box for example) from a separate thread, you have to reference it somehow, and the easiest way I have found is to delegate a reference.

Essentially, what happens is the following:

Your sub-thread calls AddMsg("Something"), and then the programme will call the method, as it sees right there. When it gets to the if (InvokeRequired), it determines whether or not it actually has access to that object internally, if not, it Invoke's a delegate, which will call the method as a normal method, and reference the correct GUI items, or other non-static fields or methods.

NOTE: When using Static Fields, Methods, or other properties, this is not necessary. You can directly reference static items.


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...