6

我正在创建一个控制台程序,它可以通过模拟多个客户端来测试对高速缓存的读/写,并且已经编写了以下代码。请帮助我了解:使用C#Async等待负载测试

  • 是不是正确的方式来实现多客户端模拟
  • 我能做得更多,使之成为真正的负载测试
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); 
} 
+1

看起来没问题,WCf和其他许多服务主机会阻止来自一个发件人的太多负载,因此即使您从一台计算机上轰炸了您的服务,其他人也可以轻松访问您的服务。 –

+1

可能有些任务可以使用'Factory.StartNew'来预定,并且在大量的同步任务的情况下它们的执行将被延迟。 – cassandrad

回答

2

调整你的代码稍微查看我们在特定时间有多少个线程。

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

其结果是:一个虚拟机I从同时运行,如果我不使用提示2-10螺纹具有内部。提示 - 高达100.在真机上,我可以同时看到1000个线程。进程浏览器证实了这一点。关于hint的一些细节将会有所帮助。

+0

非常感谢您提供了一个有趣的信息,尤其是关于确保每个线程在单独的客户端上调用而不是预定的信息的提示 –

2

如果非常繁忙,那么显然您的客户必须等待一段时间才能提供服务。您的程序不会衡量这一点,因为您的秒表在服务请求开始时开始运行。

如果您还想测量请求完成前平均时间发生的情况,则应在请求发出时启动秒表,而不是在请求被服务时启动秒表。

您的程序只从线程池获取线程。如果你启动了更多的任务,那么就有线程,在TestAsync开始运行之前,一些任务将不得不等待。如果您记得Task.Run被调用的时间,则会测量此等待时间。

除了时间测量的缺陷之外,您还期望同时有多少个服务请求?线程池中是否有足够的空闲线程来模拟这个线程?如果您同时期待大约50个服务请求,并且线程池的大小只有20个线程,那么您将永远不会同时运行50个服务请求。反之亦然:如果你的线程池比预期的同时服务请求的数量大,那么你将测量比实际情况更长的时间。

考虑更改线程池中的线程数,并确保没有其他人使用任何线程池。

+0

感谢您的好的细节,将会有所不同 –