-1

I have a WPF app and I would like to change the position of a rectangle every second for an infinite amount of time (or until the application is closed)

Right now I have this

while(true)
{
     rect.Margin = new Thickness(rect.Margin.Left + 10, 0, 0, 0);
     System.Threading.Thread.Sleep(100);
}

but this seems to just hang the application because it just delays the application by 100ms every single update

I want a while true loop that wont hang the application and fires every 1 second

human
  • 33
  • 7

1 Answers1

1

It's hard to tell from the little bit of code that you shared. But it is most likely because your while loop is on the UI thread, so when you call System.Threading.Thread.Sleep(100), you are putting the UI thread to sleep and therefore it visually hangs. The same will occur when you call Task.Delay with Wait() because it will synchronously run, and hold up the UI thread.

Instead, try using async/await. This will free up the thread and allow other operations to perform on the same thread while the code is on the await line.

private async Task MyWhileLoopMethod()
{
    while(true)
    {
        rect.Margin = new Thickness(rect.Margin.Left + 10, 0, 0, 0);
        await System.Threading.Tasks.Task.Delay(1000);
    }
}

You will need to make every call up the chain async/await as well. So for example, if you had a Button_Click event that triggered this rectangle movement, then at the top of the chain you would do this:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await MyWhileLoopMethod();
}
Tam Bui
  • 2,940
  • 2
  • 18
  • 27