How can I make `await …` work with `yield return` (i.e. inside an iterator method)?

后端 未结 3 615
广开言路
广开言路 2020-12-05 01:11

I have existing code that looks similar to:

IEnumerable GetStuff()
{
    using (SqlConnection conn = new SqlConnection(connectionString))
           


        
3条回答
  •  被撕碎了的回忆
    2020-12-05 01:39

    Speaking strictly to async iterator's (or there possibility) within the context of a SqlCommand in my experience I've noticed that the synchronous version of the code vastly outperforms it's async counterpart. In both speed and memory consumption.

    Perhaps, take this observation with a grain of salt as the scope of the testing was limited to my machine and local SQL Server instance.

    Don't get me wrong, the async/await paradigm within the .NET environment is phenomenally simple, powerful and useful given the right circumstances. After much toiling however, I'm not convinced database access is a proper use case for it. Unless of course you're needing to execute several commands simultaneously, in which case you can simply use TPL to fire off the commands in unison.

    My preferred approach rather is to take the following considerations:

    • Keep the units of SQL work small, simple and compose-able (i.e. make your SQL executions "cheap").
    • Avoid doing work on the SQL Server that can be push upstream to the app-level. A perfect example of this is sorting.
    • Most importantly, test your SQL code at scale and review Statistics IO output/execution plan. A query which runs quickly at 10k record, may (and probably will) behave entirely differently when there a 1M records.

    You could make the argument that in certain reporting scenarios, some of the above requirements just aren't possible. However, in the context of reporting services is asynchronous-ity (is that even a word?) really needed?

    There's a fantastic article by Microsoft evangelist Rick Anderson about this very topic. Mind you it's old (from 2009) but still very relevant.

提交回复
热议问题