C# StreamReader -> ReadToEndAsync more than twice as slow as ReadToEnd

2.6k views Asked by At

I'm using a web application to display geojson on Google Maps. I don't wan't to render everything so I'm using an algorithm to only load specific portions of the geojson. The files are fairly large ranging from 5 to 84 MB with a total size of 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();
}

This method is pretty slow due to the many and large files and since they are not dependent on each other I tried to get the information asynchronously. However when using ReadToEndAsync it is nearly 2,5 times slower than ReadToEnd. I can shave some time of using BufferedStream but it is still slower than just running the code synchronously. Why is this and how can I make it perform better?

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

There are 0 answers