在研究异步Web开发概念时,特别是从这个来源,我创建了一个示例应用程序来证明这个概念。
该解决方案由2个ASP.NET Web API应用程序组成。第一个是模拟缓慢终端的应用程序;它在返回一个名为Student的自定义类列表之前等待1000ms:
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" } };
}
这里是学生类:
public class Student
{
public string Name { get; set; }
}
这个端点托管在本地主机的IIS 7中,端口号为4002。
第二个应用程序使用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());
}
它托管在本地主机上的 IIS 7 上,端口是 4001。
两个端点都按预期工作,并在大约 1 秒内返回。根据链接中的视频在13:25的时间点,异步方法应该释放其线程,最小化争用。
我正在使用 Apache Bench 对应用程序进行性能测试。下面是使用 10 个并发请求的同步方法的响应时间:
这正如我预期的那样;更多的并发连接增加了争用并延长了响应时间。然而,以下是异步响应时间:
正如您所看到的,仍然似乎存在一些争用。我希望平均响应时间更加平衡。如果我在两个端点上使用 50 个并发请求运行测试,我仍然会得到类似的结果。
基于此,似乎同步和异步方法运行速度相当(预期),未考虑异步方法中的开销,但异步方法似乎没有将线程释放回线程池。欢迎任何评论或澄清,谢谢。
async
方法实际上并不完全是异步的,你应该使用ReadToEndAsync()
。 - svick