C#压力测试 - 模拟给定的共享资源多址 [英] C# Stress Test - Simulate multiple access to a given shared resource

查看:279
本文介绍了C#压力测试 - 模拟给定的共享资源多址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可以模拟/压力测试大约100名用户在C#单元测试访问一个给定的共享资源(如数据库)?

How can you simulate/stress test about 100 users accessing a given shared resource (e.g. Database) in a c# unit test?

推荐答案

假设你正在访问实时DB你在集成测试范围是。最简单的方法是从多个线程访问资源。例如:

Assuming you're accessing real DB you're in the scope of integration tests. The simplest way is to access the resource from multiple threads. For example:

[Test]
public void SimpleStressTest()
{
    bool wasExceptionThrown = false;
    var threads = new Thread[100];
    for(int i = 0; i < 100; i++)
    {
        threads[i] = 
            new Thread(new ThreadStart((Action)(() =>
            {
                try
                {                        
                    AccessDB();
                }
                catch(Exception)
                {
                    wasExceptionThrown = true;
                }

            })));
    }

    for(int i = 0; i < 100; i++)
    {
        threads[i].Start();
    }    
    for(int i = 0; i < 100; i++)
    {
        threads[i].Join();
    }

    Assert.That(wasExceptionThrown, Is.False);
}

这测试不确定性的,因为你无法控制线程流动。如果你想确保,例如,100个连接可同时打开,你可以放置一个钩的逻辑 ACCESSDB()这将迫使它。等它关闭到数据库的连接之前

This test is not deterministic since you can't control the threads flow. If you want to make sure, for example, that 100 connections can be opened at the same time, you can place a hook in the logic of AccessDB() which will force it to wait before it closes the connection to the DB.

例如,而不是以前的螺纹操作:

For example, instead of the previous thread action:

try
{                        
    AccessDB(sychObject);
}
catch(Exception)
{
    wasExceptionThrown = true;
}



开始的所有线程后,请确保您有100个线程在等待上的 sychObject ,然后才释放出来,并加入线程。同样可以通过的逻辑来实现CloseConnection()(例如)的虚拟的写对继承类的考验等待在 CloseConnection()。例如:

After starting all the threads make sure you have 100 threads waiting on the sychObject and only then release it and join the threads. The same can be achieved by making the logic of CloseConnection() (for example) virtual and write the test against an inheriting class the waits in CloseConnection(). For example:

public class DataBase
{
    public void AccessDB()
    {
        // Do logic here before closing connection
        CloseConnection();
    }

    protected virtual void CloseConnection()
    {
        // Real Logic to close connection
    }
}

public class FakeDataBase : DataBase
{
    ManualResetEvent sychObject;

    public FakeDataBase(ManualResetEvent sychObject)
    {
        this.sychObject = sychObject;
    }

    override protected void CloseConnection()
    {
        sychObject.WaitOne();
        base.CloseConnection();
    }
}

这篇关于C#压力测试 - 模拟给定的共享资源多址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆