NoviceMe
NoviceMe

Reputation: 3256

Winform label text not showing

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?

Upvotes: 4

Views: 6908

Answers (4)

Loudenvier
Loudenvier

Reputation: 8804

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

Upvotes: 5

urlreader
urlreader

Reputation: 6615

as above says, it is because the sleep, the UI does not have time to update it yet.

however, you do not have to use timer. DoEvents() gives it some time to update UI.

try

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

Upvotes: 4

Keysharpener
Keysharpener

Reputation: 504

Avoid pausing threads in UI classes. The last thing you want is an unresponsive interface!

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

This is because the Thread.Sleep causes the application to pause the current thread - this means that during these 50 seconds no updates occur on the form.

What you need to do to achieve what you want is to start a timer that elapses after 50 seconds and in the timer's code, hide the form.

The timer can be a Windows Forms timer component placed on the form.

Upvotes: 3

Related Questions