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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With