Thread Label Updating

devhelios

New member
Joined
Oct 26, 2021
Messages
2
Programming Experience
Beginner
Hi,

On my Win Form App, I'm starting a new thread for my Splash Screen (and when loading some component on my main form).

I wanna be able to update a label on the new thread. I try with invoke, delegate and similar thing but i'm not able to do it.

I'm now out of ressource. Can anyone help me with this ? May be my code is not the best to do this ?

My frmSplashScreen form containt 1 label named metroLabel4 and this it this one I wanna update from the "// Code for loading component go here" section.

Thanks in advance.


C#:
        public frmMain()
        {
            Thread t = new Thread(new ThreadStart(Loading)); // Starting thread
            t.Start();
            InitializeComponent();

            // Code for loading component go here
           
            t.Abort();//Complete
        }

        //Start splash screen
        void Loading()
        {
            frmSplashScreen frm = new frmSplashScreen();
            Application.Run(frm);
        }
 
Last edited:
Stop and consider what you are doing. Your frmMain was launched by using Application.Run() in your main.cs. Now in your frmMain's constructor you are starting another thread and then in that new thread you are calling Application.Run() once more? Assuming that the singleton Application object will let you call Run() from two separate threads is that really a wise idea considering that the singleton has only one MainForm property that is fed by the message pump built into the Run() method.

I'm currently at work right now so a lot of sites are blocked, you'll want to search for Jessica Fosler's old blog posts about ApplicationContext and the correct way to run tray applications. In the same posts, she also offers ways to correctly do splash screens. What it comes down to is setting the splash screen as the initial MainForm and then later swapping in your real application's form.

Also as an aside, Thread.Abort() should only be used as a last resort because that prevents the thread from doing any cleanups. You should send a signal to the other thread that is should stop running. It's up to you if you want to do it via global boolean, an event, a mutex, or a semaphore. Any which way, you want to let that other thread end gracefully.
 
Last edited:
Thanks for the answer. As a beginner, I take a tutorial to do the splash screen and that's what it was written to do.

I will certainly do the research about Jessica Fosler's !

Thanks :)
 
That's a bad tutorial.

Jessica worked on the Windows team and helped with the .NET Framework. She knows what she's talking about.
 
Back
Top Bottom