Code Throwing InvalidOperationException While Setting Text To label Programmatically

851 views Asked by At

Here Is The Code Which Throws An InvalidOperationExecption Every Time I Try To Set Text To My Label Programmatically...

using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Project
{
public partial class Splash : Form
{
    public Splash()
    {
        InitializeComponent();
        Thread quit = new Thread(Quit);
        Thread Load = new Thread(LoadIt);
        Load.Start();
        quit.Start();
    }

    private void Splash_FormClosing(object sender, FormClosingEventArgs e)
    {
        Application.Exit();
    }

    public static void Quit()
    {
        Thread.Sleep(3000);
        Application.Exit();
    }

    public void LoadIt()
    {
        Thread.Sleep(500);
        Loading.Text = "Loading..";
    }
    }
}

Why This Code Throws An Exception? What's Wrong In This?

"Loading" Is The Name Of My Label

enter image description here

2

There are 2 answers

1
Kelson Ball On

Use the threading dispatcher to execute code on the same thread as the UI

Thread.Sleep(500);
System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(() => { 
    Loading.Text = "Loading...";
});

Most UI libraries are not thread safe, so you must make UI changes from their own thread.

0
Kevin Smith On

Take advantage of the TPL and use the Task class, this will switch back to the context thread after to resume execution

public partial class Splash : Form
{
    public Splash()
    {
        InitializeComponent();
    }

    private void Splash_FormClosing(object sender, FormClosingEventArgs e)
    {
        Application.Exit();
    }

    private void Splash_OnLoad(object sender, FormClosingEventArgs e)
    {
        await Task.Delay(500);

        Loading.Text = "Loading..";

        await Task.Delay(3000);

        Application.Exit();
    }
}