Domanda

I want to just show a Message for a short time in TextBlock. I'm using this code

Label1.Text = "Wrong Password!";
System.Threading.Thread.Sleep(5000);
Label1.Text = " ";

But this is not working, if anyone have other better logic then please do Answer!

È stato utile?

Soluzione

The code above will sleep the UI thread, so what essentially happens is this:

  1. Request that label text be set to "Wrong Password!" (not updated till next UI thread tick)
  2. Sleep for 5 seconds
  3. Request that label text be set to ""
  4. UI thread ticks, label is set to ""

To work around this do something like:

Label1.Text = "Wrong Password!";

// start a new background thread
new Thread(new ThreadStart(() =>
{
    Thread.Sleep(5000);

    // interacting with Control properties must be done on the UI thread
    // use the Dispatcher to queue some code up to be run on the UI thread
    Dispatcher.BeginInvoke(() =>
    {
        Label1.Text = " ";
    });
})).Start();

This will:

  1. Request that the label text be set to "Wrong Password!"
  2. Start a different thread that sleeps for 5000ms
  3. In the meanwhile the UI Thread continues to execute so the Label gets updated to "Wrong Password!"
  4. 5000ms passes and the background requests that the label text be cleared
  5. the UI thread ticks and updates the label
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top