Question

I want to avoid blocking the executing thread by slow database read , and I like BLToolkit DataAccessor very much

public abstract class PersonAccessor : DataAccessor
{
    [SqlText(@"SELECT * FROM Person WHERE FirstName = @firstName")]
    public abstract List<Person> GetPersonListByFirstName(string @firstName);

    [SprocName("sp_GetPersonListByLastName")]
    public abstract List<Person> GetPersonListByLastName(string @lastName);
}

Is it possible to use async operation for BLToolkit DataAccessor?

Hope it is able to return Task<T> and I can use await from C# 5.0

Br.

Was it helpful?

Solution

You may combine the Async attribute which provides the Begin End pattern and turn it into Task like this (not tested) :

public abstract class PersonAccessor : DataAccessor
{
    [SqlText(@"SELECT * FROM Person WHERE FirstName = @firstName")]
    public abstract List<Person> GetPersonListByFirstName(string @firstName);

    [Async]
    public abstract IAsyncResult BeginGetPersonListByFirstName(string @firstName, AsyncCallback callback, object state);

    [Async]
    public abstract List<Person> EndGetPersonListByFirstName(IAsyncResult asyncResult);

    public Task<List<Person>> GetPersonListByFirstNameAsync(string @firstName)
    {
        return Task.Factory.FromAsync(
            BeginGetPersonListByFirstName(),
            EndGetPersonListByFirstName,
            @firstName, 
            null);
    }
}

public class TestClass 
{
    public List<Person> AwaitTest(PersonAccessor personAccessor, string @firstName)
    {
        return await personAccessor.GetPersonListByFirstNameAsync(@firstName);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top