0

In regard to the XmlSerializer I wonder if for a WebAPI it matters if the operation in this case is sync or async. The point is I haven't really saw anyone using ReadToEndAsync, so far what I have saw is everyone uses the sync version. There for my question which one am I supposed to use. Maybe this question depends on the context if we are looking the hole web API or maybe if we are looking one specific request and inside that request we have multiple parts that we want to deserialise.

Maybe since my scenario takes multiple strings and tries them to parse into xml I should use ReadToEndAsync + WhenAll to get better performance?

Please if possible give me some clarification on the pros and cons.

public static async Task<string> SerializeToXmlDefaultAsync(T value, Type type = null)
{
    var settings = new XmlWriterSettings
    {
        Indent = true,
        Async = true
    };

    var ms = new MemoryStream();
    using var writer = XmlWriter.Create(ms, settings);
    XmlSerializer cs;
    if (type == null)
        cs = new XmlSerializer(typeof(T));
    else cs = new XmlSerializer(type);

    cs.Serialize(writer, value);

    ms.Flush();
    ms.Seek(0, SeekOrigin.Begin);
    var sr = new StreamReader(ms);
    return await sr.ReadToEndAsync(); // Should this be async and why?
}
  • https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await – JamesS Oct 15 '21 at 09:52
  • So since this is long running operation (in a sence that the processor needs to do the work) I should use the sync version? I was aware of that but could not really find a clear statement anywhere. I wondered if for this reason there is a other case I'm not aware of. Please confirm. – Muhamed Karajic Oct 15 '21 at 09:55
  • It depends on if you care about what it returns. If you are wanting to check against information in the file, I would use synchronous, but if it's just a fire and forget, use async. – JamesS Oct 15 '21 at 09:56
  • If that's the only pro then I guess my question is answered. Thank you very much. If you can write your answer below and I'll close this question. – Muhamed Karajic Oct 15 '21 at 10:03

0 Answers0