Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Test using C# Async Await

I am creating a console program, which can test read / write to a Cache by simulating multiple clients, and have written following code. Please help me understand:

  • Is it correct way to achieve the multi client simulation
  • What can I do more to make it a genuine load test
void Main()
{

    List<Task<long>> taskList = new List<Task<long>>();

    for (int i = 0; i < 500; i++)
    {
      taskList.Add(TestAsync());
    }

    Task.WaitAll(taskList.ToArray());

    long averageTime  = taskList.Average(t => t.Result);

}

public static async Task<long> TestAsync()
{
    // Returns the total time taken using Stop Watch in the same module
    return await Task.Factory.StartNew(() => // Call Cache Read / Write);
}
like image 584
Mrinal Kamboj Avatar asked Aug 04 '16 17:08

Mrinal Kamboj


1 Answers

Adjusted your code slightly to see how many threads we have at a particular time.

static volatile int currentExecutionCount = 0;

static void Main(string[] args)
{
    List<Task<long>> taskList = new List<Task<long>>();
    var timer = new Timer(Print, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

    for (int i = 0; i < 1000; i++)
    {
        taskList.Add(DoMagic());
    }

    Task.WaitAll(taskList.ToArray());

    timer.Change(Timeout.Infinite, Timeout.Infinite);
    timer = null;

    //to check that we have all the threads executed
    Console.WriteLine("Done " + taskList.Sum(t => t.Result));
    Console.ReadLine();
}

static void Print(object state)
{
    Console.WriteLine(currentExecutionCount);
}

static async Task<long> DoMagic()
{
    return await Task.Factory.StartNew(() =>
    {
        Interlocked.Increment(ref currentExecutionCount);
        //place your code here
        Thread.Sleep(TimeSpan.FromMilliseconds(1000));
        Interlocked.Decrement(ref currentExecutionCount);
        return 4;
    }
    //this thing should give a hint to scheduller to use new threads and not scheduled
    , TaskCreationOptions.LongRunning
    );
}

The result is: inside a virtual machine I have from 2 to 10 threads running simultaneously if I don't use the hint. With the hint — up to 100. And on real machine I can see 1000 threads at once. Process explorer confirms this. Some details on the hint that would be helpful.

like image 78
cassandrad Avatar answered Oct 05 '22 04:10

cassandrad