0

I know that when calling asynchronous methods a Thread is allocated from the pool and this has a cost.

XmlReader has asynchronous implementations:

using (var r = XmlReader.Create(fs, new XmlReaderSettings() { Async = true }))
{
    while (await r.ReadAsync())
    {
        if (r.IsStartElement())
        {
            switch (r.Name)
            {
                case "a": var a = await r.ReadElementContentAsStringAsync(); break;
                case "b": var b = await r.ReadElementContentAsStringAsync(); break;    
                case "c": var c = await r.ReadElementContentAsStringAsync(); break;
            }
        }
    }
}

Wouldn't it be a waste of processing to allocate threads in the pool to perform a process as simple as reading an xml element?

I imagine that asynchronous reads in xml should be used only when the content of the tag is known to be large, such as strings in base64, etc.

The code above written synchronously, wouldn't be more performance? Of course, reading about 5,000 xml files or a single large xml file.

Vinicius Gonçalves
  • 2,514
  • 1
  • 29
  • 54
  • 3
    `I know that when calling asynchronous methods a Thread is allocated from the pool and this has a cost.` where did you get this information ? – TheGeneral Jan 19 '19 at 23:48
  • 2
    It depends. If you're just reading one file then indeed you won't gain anything from using the asynchronous version. If you're reading 100 files in parallel then you should definitely go for async. When it comes to performance there is really only one rule: measure, then make your decision – Kevin Gosse Jan 19 '19 at 23:48
  • I voted for closing as this will vary from one use case to another, as people said measure what you want to do. – Ivan Ičin Jan 19 '19 at 23:56
  • 1
    Your question might be based on incorrect assumptions, take a look at [What is the difference between asynchronous programming and multithreading?](https://stackoverflow.com/q/34680985/3744182) and [Async/Await vs Threads](https://stackoverflow.com/q/15148852/3744182). But see also [Async I/O intensive code is running slower than non-async, why?](https://stackoverflow.com/q/28544557/3744182) and [Can using async-await give you any performance benefits?](https://stackoverflow.com/q/36683468/3744182). – dbc Jan 20 '19 at 00:08
  • Asynchronous method has advantage in three cases 1) You have to access data quickly before it is overridden. An example where a UART has a small buffer like 8 bytes and you must read the data before it is lost 2) When you are trying to run items in parallel to get improved performance. 3) Where blocking in synchronous mode will prevent other methods from running. Like in a form project where blocking may lock up the form. – jdweng Jan 20 '19 at 11:17

0 Answers0