Q:

Read a json file async vs 2017 .net core

I have a bunch of json files that I need to read.
Is it possible to convert this code to be fully async?
Is there a better way to do this?
public static T LoadJsonFile<T>(this Assembly assembly, string fullFilename) where T : new()
    {
        T result;

        Stream stream = assembly.GetManifestResourceStream(fullFilename);

        using (var reader = new StreamReader(stream))
        {
            result = JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
        }
        return result;
    }

THis is not a duplicate because I am asking how to read a json file not using HTTPCLIENT
any samples?
thanks

A:

You can make the IO potentially asynchronous by using ReadToEndAsync:
public static async Task<T> LoadJsonFile<T>(this Assembly assembly, string fullFilename)
    where T : new()
{
    using (var stream = assembly.GetManifestResourceStream(fullFilename))
    {
        using (var reader = new StreamReader(stream))
        {
            string json = await reader.ReadToEndAsync();
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}

However, there are a number of caveats about this:

The JSON parsing and deserialization is still being performed synchronously. You may find you're CPU-bound rather than IO-bound.
Not all streams can perform true asynchronous IO. I don't know whether the one returned by GetManifestResourceStream can. You may find that it ends up "faking" asynchrony in a way that doesn't help you much.
If you're trying to load thousands of files, you may well just end up with disk contention anyway. (This will depend on many factors, including what kind of disk it is, how embedded resources handled, and what your mix of files vs resources is.)

I would at least try a simple Parallel.ForEach loop as well as asynchrony, and see how that compares with the asynchronous code. Make sure you have a good way of testing the performance, and acceptance criteria so you know when you're done.

