Archive for October 2018

.Net Core, run async methods in a loop

Here is a Unittest running async method which needs to show how async can benefit when long running methods are run. It should complete in about same amount of seconds as the longest delay that was set randomly during the execution of the test.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using System.Diagnostics;

namespace Some.test
{
  public class TestAsyncTasks
  {
    // Randomizer
    Random _rnd = new Random();

    [Fact]
    /// <summary>
    /// Run fake tasks with random delay async
    /// </summary>
    public async Task RunRandomTasksAsync()
    {
      var series = Enumerable.Range(1, 5).ToList();
      var tasks = new List<Task<Tuple<int, bool>>>();
      foreach (var i in series)
      {
        Debug.WriteLine(“Starting Process=” + i);
        tasks.Add(DoWorkAsync(i));
      }

      // Loop to process the tasks one at a time until none remain
      while (tasks.Count > 0)
      {
        // Get the first task that completes
        var thetask = await Task.WhenAny(tasks);

        // Remove the selected task from the list only process it more than once.
        tasks.Remove(thetask);

        // Await the completed task
        Tuple<int, bool> tupl = await thetask;
        Debug.WriteLine(“Process=” + tupl.Item1 + ” ended”);
      }
    }

    /// <summary>
    /// Complete a fake task using random delay
    /// </summary>
    public async Task<Tuple<int, bool>> DoWorkAsync(int i)
    {
      int delay = _rnd.Next(25);
      Debug.WriteLine(“working.. process=” + i + “, delay=” + delay);
      await Task.Delay(1000 * delay);
      return Tuple.Create(i, true);
    }
  }
}