0

Using c# .NET, I'm trying to update a label in a form and reset it to empty after a few seconds, if no other update is done (in that case, the reset must be cancelled and delayed again).

I've found different solutions with cancellable tasks and updating UI after a delay, but not both combined.

This is a try, that fails when updating properties out of the UI thread:

    private CancellationTokenSource TokenClearUIMessage;

    private void SetUIMessage(string Message, string Detail, Color Color)
    {
        if (TokenClearUIMessage != null) TokenClearUIMessage.Cancel();

        TokenClearUIMessage = new CancellationTokenSource();
        Task.Delay(1000).ContinueWith(t => {
            LblMessage.Text = "-"; // <= THROWS EXCEPTION
            LblMessage.BackColor = Color.White;
        }, TokenClearUIMessage.Token);

        LblMessage.Text = Message;
        LblMessage.BackColor = Color;
        LblDetails.Text = Detail;
    }

How can I proceed? Thank you.

Edit: Recommended solution was useful (How do I update the GUI from another thread?) but not completed I still missed the cancellation option but leaded me to the right solution.

Servy
  • 202,030
  • 26
  • 332
  • 449
Mario M.
  • 416
  • 2
  • 10
  • 1
    Please note that you want to take a [look at the 3rd answer](https://stackoverflow.com/a/18033198/1260204). The first 2 are still valid but considered dated. – Igor Mar 16 '18 at 13:16
  • Thank you for the reference, but it still misses the cancellation. I edited the question to include the right solution. – Mario M. Mar 19 '18 at 13:52

0 Answers0