BLToolkit - 是否能够进行异步数据库操作?

时间:2013-08-16 12:03:18

标签: bltoolkit

我想通过慢速数据库读取来避免阻塞执行线程,我非常喜欢BLToolkit DataAccessor

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);
}

是否可以对BLToolkit DataAccessor使用异步操作?

希望能够返回Task<T>,我可以使用C#5.0中的await

1 个答案:

答案 0 :(得分:2)

您可以将提供Begin End模式的Async属性与此类turn it into Task组合(未经测试):

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);
    }
}