Question: I want to wait till the execution of one loop is completed in below code.Dont intended to process next item in list until one is done. How to ensure that execution inside foreach loop is completed once at a time or one loop at a time in the below scenario

Please note, this is a sample code only to demonstrate the issue, I know that if I remove the Task.Run from for each loop, it may work, but I need to have that task.Run in the foreach loop for some reason in my code.

```
List<int> Items = new List<int>();
Items.Add(1);
Items.Add(2);
Items.Add(3);

foreach(var itm in Items)
{
 Task.Run(() =>
       {
       MyFunction(itm);
       });

//  I want to wait here till one execution is complete, e.g till execution of Item with Value 1 is completed,  
//I dont' intend to execute next item value of 2 until processing with value 1 is completed.

}

private void MyFunction(int value)
{    
 Task.Factory.StartNew(() =>
    {
  MyFunction2(value);

    });

}

private void MyFunction2 (int number)
{
// do some ops 
// update UI

}

```

Answer: 
Use async await. `await` allows you to wait for a `Task` to finish without blocking the thread (thus your application won't freeze)

```cs
foreach(var itm in Items)
{
    await MyFunction(itm);
}

// you must return Task to await it. void won't work
private Task MyFunction(int value)
{
    // Task.Run is preferred over Task.Factory.StartNew,
    // although it won't make any difference
    return Task.Run(() => MyFunction2(value));
}

```

Also don't forget to make the method containing the foreach loop `async Task`. You can await Tasks only in `async` methods. Return type should be `Task`, so you can later await it and possibly catch exceptions. Avoid `async void`, unless the method is an event handler.

```cs
public async Task Foo()
{
    foreach(var itm in Items)
    {
        await MyFunction(itm);
    }
}

```
Task.Run returns a Task object that represents that work. You need to call Wait on that. 

```
 var myTask = Task.Run(() =>
   {
   MyFunction(itm);
   });
  myTask.Wait();

```