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

感謝您的好的細節,將會有所不同 –