Home > OS >  Hold UI for 2 second without blocking it so user can see a change in a controller
Hold UI for 2 second without blocking it so user can see a change in a controller

Time:01-15

I have an old game I created few years back that every round give a question to the user, the user pick an option as an answer and then if the answer is right the question label will become green and if it's wrong it will become red, then it will go to the next round, something like that:

public void CheckAnswer(string answer)
{
  if(answer == currectAnswer)
  {
   answerLabel.ForeColor = Color.Green;
  }
  else
  {
   answerLabel.ForeColor = Color.Red;
  }
  NextRound();
} 

Now if I run the code like that the user will not see the color change becuase the next round will start too fast, if I try to use something like thread.sleep(); it will not chnage the color even if it is called after the color change line and it will also block the UI.

So in the past I manage to use the Dispatcher class to create this method:

        public static void UIWait(double seconds)
        {
            var frame = new DispatcherFrame();
            new Thread((ThreadStart)(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(seconds));
                frame.Continue = false;
            })).Start();
            Dispatcher.PushFrame(frame);
        }

It did the job perfectly.

Issue is that now I'm upgrading the game to .net core (.net 6.0) and the Dispatcher class is not supported anymore.

I need to find something else that can do the same job and hold the UI for 2 second without blocking it so the user will see the change of color before going to the next round.

Thanks for the help!

CodePudding user response:

You should be able to use async and await:

public async void CheckAnswer(string answer)
{
  answerLabel.ForeColor = (answer == currectAnswer) ? Color.Green : Color.Red;
  await Task.Delay(2000); // two second delay
  NextRound();
} 
  • Related