Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winform label text not showing

Tags:

c#

winforms

I have following code:

Hide()
if(a > b)
{
label.Text = "a is greater than b";
Show();
Thread.Sleep(50000);
}

What i am trying to do is hide the winform as soon as app starts. If a>b at any point it will show the winform with that message in the label for 50 second and will hide again. Also label is set to autosize = true;

Above code works but label is not showing any text? Also is this the right approch to show the winfor for sometime using thread sleep?

like image 893
NoviceMe Avatar asked Dec 15 '22 16:12

NoviceMe


1 Answers

Thorsten is right, Sleep is freezing the UI thread, so the UI is not refreshed, but you could also do something like this as a workaround:

Hide()
if(a > b)
{
    label.Text = "a is greater than b";
    Show();
    Refresh();
    Thread.Sleep(5000);
}

But the cleanest solution of course is:

Hide()
if(a > b)
{
    label.Text = "a is greater than b";
    Show();
    Task.Factory
        .StartNew(() => Thread.Sleep(5000))
        .ContinueWith(() => Close(), TaskScheduler.FromCurrentSynchronizationContext());
}

But don't forget to add the proper using clause to use the Task Parallel Library:

using System.Threading.Tasks;

The TPL is available in .NET 4 onwards. More info here: http://msdn.microsoft.com/en-us/library/dd460717.aspx

like image 136
Loudenvier Avatar answered Dec 27 '22 14:12

Loudenvier