4

我想避免通过慢速数据库读取阻塞执行线程,我非常喜欢 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>,我可以await从 C# 5.0 开始使用

兄弟。

4

1 回答 1

2

您可以结合提供 Begin End 模式的Async属性并将其转换为 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);
    }
}
于 2014-11-03T13:07:27.103 回答