Search code examples
.netnhibernateasynchronouslinq-to-nhibernate

How can I run NHibenate queries asynchronously?


One way to increase scalability of the server application is to run IO-bound operation (reading files, sockets, web requests, database requests etc) asynchronously. This does not mean run them in the ThreadPool which will just block threads while operation is being executed. The correct way is to use asynchronous API (BeginRead, BeginGetResponse, BeginExecuteReader etc). The problem is well described in CLR vi C# book.

Here is some article about asynchronous queries in Linq to SQL.

Are any ways to execute Nhibernate query asynchonously? What about Linq to NHibernate?

Thank you, Andrey


Solution

  • As of NHibernate v5, async is now fully supported!

    Here are some nifty examples:

    Customer customer = await session.GetAsync<Customer>(1);
    
    List<Customer> customers = await session.Query<Customer>().ToListAsync();
    
    Customer customer = await session.Query<Customer>()
    .Where(x => x.Name.Contains("Customer 1"))
    .SingleOrDefaultAsync();
    

    Updating an entity

    using (ISession session = sessionFactory.OpenSession())
    using (ITransaction transaction = session.BeginTransaction())
    {
        Customer customer = await session.GetAsync<Customer>(1);
        customer.Name = "Customer 3";
        await session.SaveOrUpdateAsync(customer);
        await transaction.CommitAsync();
    }
    

    Source article