简体   繁体   中英

Display a message for 3 seconds and then continue

I have a very short method that deletes a record from a database, and if successful, then displays a message to the user to confirm that the record has been deleted...

    private void BtnConfirmDelete_Click(object sender, RoutedEventArgs e)
    {
        // Hide "Record deleted" message
        lblDeleteSuccessful.Visibility = Visibility.Hidden;

        // Call interface method to delete record
        Record recInstance = new Record();
        recInstance.DeleteItemFromDatabase<Record>(recordNum);

        // Display "Record deleted" message
        lblDeleteSuccessful.Visibility = Visibility.Visible;
    }

I have tried...

    private void Delay()
    {
        // Will delay for 3 seconds
        DateTime timeNow = DateTime.Now;
        DateTime afterDelay = timeNow.AddSeconds(3);

        do
        {
            // Nothing !!!
        } while (timeNow != afterDelay);
    }

... and...

    private void Delay()
    {
        int delay = 3000; // Three seconds
        Thread.Sleep(delay);
    }

... but neither of these work.

Is there a way to do this??

It looks like you are using something like WPF.

If you are using Thread.Sleep, the whole thread will stop. So if you call the Delay method in the UI-Thread, it will freeze and you will not see any change in the UI.

Instead you can run the code in a different thread, so that the UI thread will be able to change the UI in the meantime.

Here is one way how to implement this using an asynchronous method:

private async Task ToggleVisibilityForThreeSeconds()
{
    lblDeleteSuccessful.Visibility = Visibility.Visible;
    await Task.Delay(3000);
    lblDeleteSuccessful.Visibility = Visibility.Hidden;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM