2013-12-16 43 views
1

我有爲wcf服務編寫的單元測試用例。現在我需要在多個線程上運行單個測試用例來檢查性能。即如果該特定方法被多個用戶調用(需要是一個自定義號碼,即從20-500的任何號碼)。我怎樣才能做到這一點? 我已經通過了Parallel.ForTask Prallel Library。但無法爲我的要求取得任何成果。需要多線程環境運行單個測試用例,即需要在多個線程上運行單個測試用例

+1

爲什麼不使用JMeter或HPLoadRunner?這些軟件旨在執行這種測試。 – tazyDevel

+0

tazyDevel我需要執行此測試通過編碼,而不是使用任何工具.. :)無論如何感謝您的迴應.. :) – Ranjit

回答

2

嗯...希望這有助於...

要在其他線程中運行的方法,簡單地做:

new System.Threading.Thread(() => YourMethodName()).Start(); 

這可以多次使用。

請注意,此方法返回void並且不會收到任何參數。

達到你想要什麼,你需要做的:

for (int i = 0; i <= 500; i++) 
{ 
    new System.Threading.Thread(() => YourMethodName()).Start(); 
} 

注:

一)有了這個代碼,你不知道當一個線程將結束。要驗證線程何時完成,您需要使用.IsAlive屬性。例如:

Thread t = new System.Threading.Thread(() => YourMethodName()); 
t.Start(); 

要驗證:

if (t.IsAlive) 
{ 
     // running 
} 
else 
{ 
    // finished 
} 

2)異常不能從外部處理。您需要處理線程內的所有異常,否則如果引發異常,程序將中斷。

3)您不能訪問線程內的UI元素。要訪問UI元素,您需要使用Dispatcher。

編輯

您可以在其他線程做更多的事情不僅僅是射擊的方法。

可以傳遞參數:

new System.Threading.Thread(() => YourMethodName(a, b, c)).Start(); 

可以比單一方法運行更多:

new System.Threading.Thread(() => 
{ 
    YourMethodName(a, b, c); 
    OtherMethod(a);   
}).Start(); 

而且你可以收到值從線程返回:

int x = 0; 
new System.Threading.Thread(() => { x = YourMethodName(); }).Start(); 

要知道x何時從線程接收到值,可以這樣做(讓我們假設一個int):

int x 
{ 
    set { VariableSetted(value); } // fire the method 
} // put it in global scope, outside the method body 

new System.Threading.Thread(() => { x = YourMethodName(); }).Start(); 

和運行時該線程返回值的方法:

public void VariableSetted(int x) 
{ 
    // Do what you want with the value returned from thread 
    // Note that the thread started this method, so if you need to 
    // update UI objects, you need to use the dispatcher. 
} 

如果您正在使用WPF使UI我不知道,但如果是,更新屏幕,你可以這樣做:

new System.Threading.Thread(() => 
{ 
    string result = YourMethodName(); 
    this.Dispatcher.Invoke((Action)(() => { yourTextBox.Text = result; })); 
}).Start(); 

你也可以sta rt嵌套線程(線程內線程)。

+0

當試圖執行負載測試時,你也應該考慮增加一些額外的等待時間(固定或隨機)在你的多個測試之間。在大多數情況下,從一個簡單的循環中發出500個呼叫不可能像情景一樣成爲產品。 – tazyDevel

+0

@tazyDevel爲什麼? – Gusdor

+0

我認爲這取決於每次通話需要完成的時間。如果這些呼叫速度很快,那麼最好儘可能快地發起呼叫,以確保所有呼叫將同時運行。這是負載測試的目標,不是嗎? – Guilherme