• 16
• 15
• 12
• 9
• 10

# C# Console Application Invoke Main Thread?

This topic is 3959 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

C# Gurus, In a Windows Application, when multiple threads are used, I know that it’s necessary to invoke the main thread to update GUI components, as shown in code below. How is this done in a Console Application? For example, I have two threads, a main and a secondary thread. The secondary thread is always listening to data from some source; when data arrives, the secondary thread passes the data to the main thread, so the main thread can write the data to a file while the secondary thread is keep on listening for new data.
        private void updateForm(string data)
{
if (this.InvokeRequired)
{
object[] obj = {data};
this.Invoke(new updateFormDelegate(updateForm), obj);
}
else
{
txtBox.Text = data;
}
}



##### Share on other sites
Most of my multithreading experience has been in console applications, and I've never had to do such a thing. It just sounds like a specific requirement for winforms.

##### Share on other sites
Quote:
 Original post by faculaganymedeC# Gurus,In a Windows Application, when multiple threads are used, I know that it’s necessary to invoke the main thread to update GUI components, as shown in code below.How is this done in a Console Application? For example, I have two threads, a main and a secondary thread. The secondary thread is always listening to data from some source; when data arrives, the secondary thread passes the data to the main thread, so the main thread can write the data to a file while the secondary thread is keep on listening for new data.*** Source Snippet Removed ***

This sounds like a consumer producer pattern. You should be using a thread safe queue or other collection to store the elements you've read in, you could use an event or other synchronization object to notify the main thread that there is data waiting to be processed.

The reason winforms has the delegate invocation requirement is that GUI objects cannot have their state changed in a thread other than the one they were created in. It's a win32 thing. Therefore to get around it they use the invocation method, which actually just posts a message to the threads message pump, which then invokes the delegate from the main thread when it gets to that message. You could implement something similar as well for your application if you wanted.