2013-12-16 38 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