C#StreamReader - > ReadToEndAsync的速度是ReadToEnd的两倍多

时间:2018-03-08 20:04:12

标签: c# async-await geojson streamreader geojson.net

我正在使用网络应用程序在Google地图上显示geojson。我不想渲染所有内容,所以我使用算法只加载geojson的特定部分。这些文件相当大,范围从5到84 MB,总大小为227 MB。

[HttpGet]
public async Task<IHttpActionResult> GetCurrentElectoralDistrict([FromUri] Point point)
{
    var task1 = GetCurrentFeature(point, "geojson1");
    var task2 = GetCurrentFeature(point, "geojson2");
    var task3 = GetCurrentFeature(point, "geojson3");
    var task4 = GetCurrentFeature(point, "geojson3");
    var task5 = GetCurrentFeature(point, "geojson3");

    await Task.WhenAll(task1, task2, task3, task4, task5);

    var result1 = await task1;
    var result2 = await task2;
    var result3 = await task3;
    var result4 = await task4;
    var result5 = await task5;

    //Modify features

}

private async Task<GeoJSON.Net.Feature.Feature> GetCurrentFeature(Point point, string geoJsonFileName)
{
    var path = HostingEnvironment.MapPath("~/");

    using (var reader = File.OpenText($"{path}\\GIS\\{geoJsonFileName}.geojson"))
    {
        //The only used await in the method. Therefore the method will run 
        //synchronously if await is removed and ReadToEnd is used.
        var json = await reader.ReadToEndAsync();
        //Handle json
    }
    //Same result using BufferedStream synchronously
    //using (FileStream fs = File.Open($"{path}\\GIS\\{geoJsonFileName}.geojson", FileMode.Open, FileAccess.Read, FileShare.Read))
    //using (BufferedStream bs = new BufferedStream(fs))
    //using (StreamReader sr = new StreamReader(bs))
    //{
    //    var json = await reader.ReadToEndAsync();
}

由于许多大文件,这种方法非常慢,因为它们彼此不依赖,所以我试图异步获取信息。但是,当使用ReadToEndAsync时,它比ReadToEnd慢近2.5倍。我可以节省使用BufferedStream的时间,但它仍然比仅同步运行代码慢。为什么会这样,我怎样才能让它表现更好?

Get request in seconds:
+----------------+----------------+------------------------------------+
|   ReadToEnd    | ReadToEndAsync | ReadToEndAsync with BufferedStream |
+----------------+----------------+------------------------------------|   
| 20.84          | 52.60          | 29.65                              |
| 19.87          | 51.03          | 29.64                              |
| 20.51          | 49.69          | 29.42                              |
+----------------+----------------+------------------------------------+

0 个答案:

没有答案