I want to add a delay after every iteration in a foreach loop, so the Treat method gets called only every 2 seconds. I do not want to use Thread.Sleep
because I want to still be able to use my program while the loop is running. I'm trying to tell the foreach loop to wait 2 seconds before doing the next iteration.
Here's what I have so far:
public async void HandlingAsync(ListViewItem woodItem)
{
IList<ListViewItem> woodList = new List<ListViewItem>();
woodList.Add(woodItem);
foreach(ListViewItem Item in woodList)
{
await Task.Delay(2000);
Treat(Item);
}
}
public void Treat(ListViewItem woodItem)
{
woodItem.SubItems[3].Text = "dried";
woodItem.SubItems[4].Text = "Ok";
}
This doesn't work because the await
command doesn't affect the foreach loop, only the commands inside of it. I can confirm that, because the ListView changes its items all at the same time, while it should change one item and wait 2 seconds before changing the next item.
EDIT: Marc Gravell ist right. The foreach loop absolutely respects the await
command. So his answer works 100%. My problem was neither in the foreach loop nor in the await
command. It didn't work because my HandlingAsync Method got called multiple times. This results in calling the Treat Method almost instantly muliple times. That means, that every woodItem got changed at the same time with a delay of 2 seconds. To solve this, the HandlingAsync should only be called once. Thanks for your help.