请告诉我从多个线程的单元测试的最好方法? [英] Whats the best way to unit test from multiple threads?
问题描述
这种从另一个问题,是继我的。
基本上,一旦我的代码访问该文件(将审查在一分钟内回答有)什么是最好的办法< STRONG>测试呢?
我想创建刚刚滋生大量的 BackgroundWorker的的或东西,告诉他们所有加载/保存文件,并测试了不同的文件/对象大小。然后,得到响应从螺纹回看它是否失败/成功/让世界内爆等。
你们可以提供的最佳方式有任何建议进场这个?正如我前面所说,这是所有还挺新的给我:)
修改
以下的ajmastrean's 后:
我使用一个控制台应用程序与Debug.Asserts测试:)
更新
我原来用的 BackgroundWorker的处理线程(因为我是从Windows开发习惯了)我很快意识到,当我执行,其中多个OPS(线程)需要完成,然后继续测试,我意识到这将是一个黑客位得到它这样做的。
然后,我跟进的 ajmastrean 的职位和意识到我真正应该使用的发类并发操作的工作。现在我将重构使用这种方法(尽管不同的方法)。
在.NET中,线程池
线程不会返回没有设置达的ManualResetEvent
s或的AutoResetEvent
秒。我觉得这些矫枉过正的快速测试方法(更不用说那种复杂的创建,设置和管理)。后台工作是一个也有点复杂的回调和这样的。
东西我发现,工作原理是
- 创建线程的数组。
- 设置每个线程的
的ThreadStart
方法。 - 开始每个线程。
- 加入的所有线程(块当前线程,直到所有其他线程完成或中止)
<预类=郎-CS prettyprint-覆盖>
公共静态无效MultiThreadedTest()
{
导线[]线程=新主题[统计]
的for(int i = 0; I< threads.Length;我++)
{
线由[i] =新主题(DoSomeWork());
}
的foreach(在线程的线程的线程)
{
thread.Start();
}
的foreach(在线程的线程的线程)
{
的Thread.join();
}
}
this kind of follows on from another question of mine.
Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it?
I am thinking of creating a method which just spawns lots of BackgroundWorker's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.
Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)
Edit
Following ajmastrean's post:
I am using a console app to test with Debug.Asserts :)
Update
I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.
I then followed up on ajmastrean's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
In .NET, ThreadPool
threads won't return without setting up ManualResetEvent
s or AutoResetEvent
s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.
Something I have found that works is
- Create an array of threads.
- Setup the
ThreadStart
method of each thread. - Start each thread.
- Join on all threads (blocks the current thread until all other threads complete or abort)
public static void MultiThreadedTest()
{
Thread[] threads = new Thread[count];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(DoSomeWork());
}
foreach(Thread thread in threads)
{
thread.Start();
}
foreach(Thread thread in threads)
{
thread.Join();
}
}
这篇关于请告诉我从多个线程的单元测试的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!