.net - Is it possible to invoke on a waiting thread? -


I have a situation where I have to wait for the main thread, while other threads can apply to the main thread without calling Application.

The following code shows what I try to achieve, except that the main thread and the data loading thread are creating dead locks.

  Fixed class programs {/// & lt; Summary & gt; Main entry point for the application /// & lt; / Summary & gt; [STAThread] Fixed Zero Main () {Application.EnableVisualStyles (); Application.SetCompatibleTextRenderingDefault (wrong); Var form 1 = new form 1 (); Form1.Show (); Thread loadDataThread = new thread ((=) {// load data that is a long time string title = load data (); form1.Invoke (action) representative {form1.Text = title;})}}; LoadDataThread. Name = "Data Loading Thread"; loadDataThread.Start (); // Wait for loading to load (deadlock) loadDataThread.Join (); // Apply more stuff. Wait ();} Private static string LoadData () {Thread Sleep (1000); Return "Hello Thread";}}  

Thanks

why just works Because the Windows Forms application has a message loop running for the entire lifetime of the application. If you are blocked on the thread. Join, then the message is not processing the loop message, which means it will call your call

In this some frameworks which do pump messages, but you can not trust them (and they should not) because they Re-create bugs to enter, which is a huge pain to resolve.

Instead, while waiting for you to load the data, by blocking the UI thread, you should let it run in the background as it shows your splash screen. Then in the end you can use BeginInvoke to close the spine screen and open the main screen or whatever you want to do at the end of the loading, whatever you want to do. Something like this ...

  Fixed zero main () {Application.EnableVisualStyles (); Var splashscreen = new form 1 (); Var main screen = new form 2 (); SplashScreen.Show (); ThreadPool.QueueUserWorkItem (Rep {LoadLotsOfData ()} splashScreen.BeginInvoke (Representative {splashScreen.Close ()} Show the main screen. ();})}} Application. Run ();}  

Comments