C# Invoke control from different thread?

How the invoke normally works is: With e.g. Application startup, you create a form which displays the log. This is on the main thread; Then, when you need to log, you get a reference to that form; Then, with Invoke, you send the log to that form. If you do need to create the form on the fly, the Invoke should also be used to create the new form.

You can do this by getting a reference to your main form and use Invoke on that form to also create the form. The problem you are seeing is because you are creating the Menu form on a non-UI thread which does not have a message loop.

Alright, so instead of creating a new form every time, I just make a reference. But if I do that, I'll have to make the Log method static. Which means I'll have to create an object called Menu in the Log method (at the moment).

Do you know how to solve that? – Nick Nov 29 '10 at 8:57 Most importantly, you need to have a way to communicate with the main thread. You have two options.1.

Create the Menu form (maybe hidden) from the main thread e.g. When you start the application.2. Create the Menu form on the fly but using Invoke on a different form, probably the main form. And yes, you need to have a reference to one of these forms.

You can do this by creating a static variable public static Menu Instance { get; private set; } which you set in the constructor Instance = this;. – Pieter Nov 29 '10 at 9:02 Thanks alot, that did the trick! I didn't know I could just call Menu.Instance.

Log("Message"); – Nick Nov 29 '10 at 9:30 You're welcome. – Pieter Nov 29 '10 at 11:10.

The answer is simpler than you think (you're missing a return, so it always runs from the wrong thread). You can simplify your code slightly: namespace Server { public delegate void Logs(string message); public partial class Menu : Form { public Menu() { InitializeComponent(); } private void InitializeComponent() { throw new NotImplementedException(); } public void Log(string message) { if (InvokeRequired) { Invoke(new Action(Log), message); return; } else { this.tbLog. Text += DateTime.

Now + ": " + message + Environment. NewLine; } } }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions