0

I am trying to perform multiple database calls using async and await features available in .NET Framework 4.5. This is the first time I am implementing this feature.

if each query is taking 7 seconds, it used to take 35 seconds(5 queries * 7 seconds). With below implementation, I was expecting it should fetch and populate controls in asp page in close to 7-9 seconds. However, it is still taking 35 seconds, proving me the synchronous behavior.

can someone please help me where I am going wrong with this below asynchronous implementation.

I appreciate on any inputs, I have been breaking my head around this since couple of days

    protected void Page_Load(object sender, System.EventArgs e)
    {
        RegisterAsyncTask(new PageAsyncTask(FillControlsAsync));
    }

    public async Task FillControlsAsync()
    {
         Task[] tasks = new Task[]{
         PopulateControlTask(query1, "controlID1"),
         PopulateControlTask(query2, "controlID2"),
         PopulateControlTask(query3, "controlID3"),
         PopulateControlTask(query4, "controlID4"),
         PopulateControlTask(query5, "controlID5")
        });

        await Task.WhenAll(tasks);
    }
    public async Task PopulateControlTask(string query, string control)
    {
       await Task.Run(() =>
           {
               DataSet ds;
               OracleCommand cmd;
               OracleDataAdapter da;
               try
               {
                   if (!Page.IsPostBack)
                   {
                       cmd = new OracleCommand(query, cn);
                       da = new OracleDataAdapter(cmd);
                       ds = new DataSet();
                       da.Fill(ds);
                       switch (control)
                       {
                           case "controlID1":
                                //some custom code for control 1
                                // like attaching the datasource to control.
                               break;
                           case "controlID2":
                               //some custom code for control 2
                               break;
                            case "controlID2":
                            //some custom code for control 3
                            break;
                            case "controlID3":
                            //some custom code for control 4
                            break;
                            case "controlID4":
                            //some custom code for control 5
                            break;
                    }
                }
            }
            catch(Exception e)
            {
                 //some error handling here
            }
        });
    }
20
  • Do you really have an empty catch block? That's an anti-pattern! Don't do that.
    – mason
    Apr 4, 2016 at 23:48
  • I'm wondering whether you want to retrieve data, or just execute query. If you need to retrieve data, above code won't work, because it just executes a task in a separate thread which doesn't return anything.
    – Win
    Apr 4, 2016 at 23:51
  • Possible duplicate of Async I/O intensive code is running slower than non-async, why?
    – mason
    Apr 4, 2016 at 23:57
  • @mason sorry, I missed adding my complete code above. I am handling the exceptions, I don't have an empty catch block in my actual code. Thank you for responding
    – knowise
    Apr 5, 2016 at 0:00
  • 1
    Not with Oracle. I pressured an Oracle dev that supported the Oracle .NET Managed Client a year or so ago that they needed to get async support working properly. He said they didn't really have it in their plans.
    – mason
    Apr 5, 2016 at 0:18

3 Answers 3

5

async and await are for asynchronous code. Normally, if you had a scalable database, you could make your db calls asynchronous and thus scale your server. Note that the primary benefit of async on ASP.NET is scalability, not response time.

However, as others have noted, Oracle doesn't support asynchronous code.

But that is immaterial, since the code you posted isn't actually asynchronous to begin with! It's what I call "fake asynchronous", because it's just pushing synchronous work off to a background thread using Task.Run instead of using naturally-asynchronous APIs. (But as already noted, in this case (that is, Oracle), you don't have any naturally-asynchronous APIs to work with).

So, what you end up with is parallelism, not asynchrony. In particular, the code is spreading itself over 5 thread pool threads to do its work.

Now, the first thing you need to do is ask yourself if you really want parallelism on the server. Your requests will take 5 threads instead of 1 (or 0). This can greatly impact the scalability of your web server (in a bad way). Also, take into consideration the capabilities of your backend. If it's a single server and these queries are all hitting a single database on a single hard drive, will parallelizing 5 of them actually produce any benefit or will it actually be just as bad if not worse due to disk contention? (You should be able to whip up a quick console app to test how your db responds with serial vs parallel requests, when idle and when under load).

I find that the vast majority of the time, the answer is "no, I do not want to bring my entire db server to its knees for this one request" - in other words, avoid parallelism on the server.

But if you have weighed the options and decided that yes, yours is one of the rare cases where parallelism is appropriate on ASP.NET, then you should ask the question that you've posted here: why are these running sequentially and not concurrently? (side note: it's sequential vs concurrent here, not synchronous vs asynchronous)

Answer: I don't know.

But I have a guess: if the database connection (cn in your code snippet) is shared, then it's likely that the db connection itself is limited to one query at a time. Other database connection systems have similar restrictions. The first thing I'd try is giving each query its own connection.

That is, if you want to parallelize your web server. Which is a big "if".

6
  • Paralleling web server is definitely a "no". Thank you for putting everything together. so, now it's my understanding that even if I were connecting to SQL Server and implement the above code, it would still NOT be a asynchronous fashion of bringing in the results from the DB unless I use asynchronous apis ?
    – knowise
    Apr 5, 2016 at 15:18
  • @CaptainRG: That is correct; you would need to use asynchronous calls instead of Task.Run. I have done this (with Azure SQL, not plain SQL Server) using EF6 asynchronous queries, and you can get them running concurrently if each one has its own db connection. That is, they use asynchronous (0-threaded) concurrency, not parallel (multi-threaded) concurrency. Apr 5, 2016 at 15:39
  • can you also please throw some light on how is the above parallel (multi-threaded ) concurrency is different from multi-threading?
    – knowise
    Apr 12, 2016 at 0:43
  • @CaptainRG: Parallelism uses multiple threads; asynchrony uses no threads. Apr 12, 2016 at 2:44
  • Sorry, Ill ask my question other way around. Earlier I was implementing asynchronous feature as above, and I have learnt that doing in that way, ill end up paralleling the webserver. Which means if I create 5 tasks for loading 5 database queries, ill end up creating 5 threads which is what we called multi threaded concurrency (as far as my above example is concerned). Having said that, is multi threading concept in c# (system.threading library) and parallelism with async is essentially similar behind the scenes? Sorry for asking the same question again.
    – knowise
    Apr 12, 2016 at 3:00
2

To follow up on other answers about Oracle's async implementation (don't have enough reputation to comment), Oracle's async methods are not truly async and just call synchronous methods under the covers, so calling them is worse for performance than the synchronous methods.

You can watch https://github.com/oracle/dotnet-db-samples/issues/144 to see if they will provide a true async implementation. As of Q1 2022, the Oracle .NET team is saying maybe Q4 2022.

1

ODP.NET Core and Managed ODP.NET 23.2 Dev Release (preview version of packages) now fully support async await: Announcing ODP.NET 23c Dev Release

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.