使用Async和Await的ASP.NET C#5异步Web应用程序

Pau*_*ney 10 c# asp.net multithreading asynchronous async-await

在研究了异步Web开发的概念之后,特别是从这个源开始,我创建了一个示例应用程序来证明这个概念.

该解决方案由2个ASP.NET Web API应用程序组成.第一个是模拟的慢端点; 它在返回一个名为Student的自定义类之前等待1000毫秒:

 public IEnumerable<Student> Get()
    {
        Thread.Sleep(1000);
        return new List<Student> { new Student { Name = @"Paul" }, new Student { Name = @"Steve" }, new Student { Name = @"Dave" }, new Student { Name = @"Sue" } };
    }
Run Code Online (Sandbox Code Playgroud)

这是学生班:

public class Student
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

此端点托管在localhost:4002上的IIS 7中.

第二个应用程序使用2个端点联系第一个,一个是同步的,另一个是异步的:

public IEnumerable<Student> Get() {
        var proxy = WebRequest.Create(@"http://localhost:4002/api/values");

        var response = proxy.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());

        return JsonConvert.DeserializeObject<IEnumerable<Student>>(reader.ReadToEnd());
    }

    public async Task<IEnumerable<Student>> Get(int id) {
        var proxy = new HttpClient();
        var getStudents = proxy.GetStreamAsync(@"http://localhost:4002/api/values");

        var stream = await getStudents;
        var reader = new StreamReader(stream);

        return JsonConvert.DeserializeObject<IEnumerable<Student>>(reader.ReadToEnd());
    }
Run Code Online (Sandbox Code Playgroud)

它在localhost:4001上的IIS 7中托管.

两个端点都按预期工作,并以大约为单位返回.1秒.基于13:25上面链接中的视频,异步方法应该释放它的Thread,从而最大限度地减少争用.

我正在使用Apache Bench对应用程序运行性能测试.以下是具有10个并发请求的同步方法的响应时间:

同步结果

这就像我期望的那样; 更多并发连接会增加争用并延长响应时间.但是,以下是异步响应时间:

异步结果

如您所见,似乎仍有一些争论.我希望平均响应时间更平衡.如果我在两个端点上运行50个并发请求的测试,我仍然得到类似的结果.

基于此,似乎异步和同步方法都以或多或少相同的速度运行(预期),没有考虑异步方法的开销,而且异步方法似乎没有释放Threads到ThreadPool.我欢迎任何评论或澄清,谢谢.

Ste*_*ary 8

我认为很有可能你没有测试你认为你正在测试的东西.从我可以收集的内容来看,您正试图通过比较时间和推断线程注入来检测回发到线程池的版本.

首先,.NET 4.5上的线程池的默认设置非常高.你不会只用10或100个同时请求来击中它们.

退一步,想一想你要测试的内容:异步方法是否将其线程返回给线程池?

我有一个演示,我展示了这个.我不想为我的演示(在我的演示笔记本电脑上运行)创建一个重负载测试,所以我提出了一个小技巧:我人为地将线程池限制为更合理的值.

完成后,您的测试非常简单:执行多个同时连接,然后执行多个加一个.在启动最后一个实现之前,同步实现必须等待一个完成,而异步实现将能够启动它们.

在服务器端,首先将线程池线程限制为系统中的处理器数量:

protected void Application_Start()
{
    int workerThreads, ioThreads;
    ThreadPool.GetMaxThreads(out workerThreads, out ioThreads);
    ThreadPool.SetMaxThreads(Environment.ProcessorCount, ioThreads);
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后执行同步和异步实现:

public class ValuesController : ApiController
{
    // Synchronous
    public IEnumerable<string> Get()
    {
        Thread.Sleep(1000);
        return new string[] { "value1", "value2" };
    }

    // Asynchronous
    public async Task<IEnumerable<string>> Get(int id)
    {
        await Task.Delay(1000);
        return new string[] { "value1", "value2" };
    }
}
Run Code Online (Sandbox Code Playgroud)

最后客户端测试代码:

static void Main(string[] args)
{
    try
    {
        MainAsync().Wait();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

    Console.ReadKey();
}

static async Task MainAsync()
{
    ServicePointManager.DefaultConnectionLimit = int.MaxValue;

    var sw = new Stopwatch();
    var client = new HttpClient();
    var connections = Environment.ProcessorCount;
    var url = "http://localhost:35697/api/values/";

    await client.GetStringAsync(url); // warmup
    sw.Start();
    await Task.WhenAll(Enumerable.Range(0, connections).Select(i => client.GetStringAsync(url)));
    sw.Stop();
    Console.WriteLine("Synchronous time for " + connections + " connections: " + sw.Elapsed);

    connections = Environment.ProcessorCount + 1;

    await client.GetStringAsync(url); // warmup
    sw.Restart();
    await Task.WhenAll(Enumerable.Range(0, connections).Select(i => client.GetStringAsync(url)));
    sw.Stop();
    Console.WriteLine("Synchronous time for " + connections + " connections: " + sw.Elapsed);

    url += "13";
    connections = Environment.ProcessorCount;

    await client.GetStringAsync(url); // warmup
    sw.Restart();
    await Task.WhenAll(Enumerable.Range(0, connections).Select(i => client.GetStringAsync(url)));
    sw.Stop();
    Console.WriteLine("Asynchronous time for " + connections + " connections: " + sw.Elapsed);

    connections = Environment.ProcessorCount + 1;

    await client.GetStringAsync(url); // warmup
    sw.Restart();
    await Task.WhenAll(Enumerable.Range(0, connections).Select(i => client.GetStringAsync(url)));
    sw.Stop();
    Console.WriteLine("Asynchronous time for " + connections + " connections: " + sw.Elapsed);
}
Run Code Online (Sandbox Code Playgroud)

在我的(8-logical-core)机器上,我看到这样的输出:

Synchronous time for 8 connections: 00:00:01.0194025
Synchronous time for 9 connections: 00:00:02.0362007
Asynchronous time for 8 connections: 00:00:01.0413737
Asynchronous time for 9 connections: 00:00:01.0238674
Run Code Online (Sandbox Code Playgroud)

这清楚地表明异步方法将其线程返回到线程池.