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();
}