关于async / await的两个实现的建议

时间:2015-02-20 17:54:54

标签: c# asynchronous async-await task

我注意到我能够通过以下两种方式获取数据(参考选项1和选项2),并想知道选择一个是否有任何影响/好处?我正在使用.NET 4.5.1并使用async / await从内部部署SQL Server加载数据。

// ***** OPTION 1 *****

// Constructor
public SomeViewModel(IProjectService projectService)
{
    Task.Run(async () => await GetAllDataAsync());
}

// This method calls out all of the other local async/await methods to download the data
private async Task GetAllDataAsync()
{
    await GetProjectDataAsync();
    await GetAssignmentDataAsync();
    ... more await calls ...
}  

// A typical method call to get data from service
private async Task GetProjectDataAsync()
{
    var projects = await projectService.GetProjectsAsync();
    this.ProjectList = projects;
}

// ***** OPTION 2 *****

// Constructor
// I call Task.Run() for all of the methods that download data
public SomeViewModel()
{
    _service = service;
    Task.Run(async () => await this.GetProjectDataAsync());
    Task.Run(async () => await this.GetAssignmentDataAsync());
    ... more Task.Run() calls ...
} 

// A typical method call to get data from service
private async Task GetProjectDataAsync()
{
    var projects = await projectService.GetProjectsAsync();
    this.ProjectList = projects;
}

编辑1:

以下是我的存储库中的async / await方法示例:

public async Task<IList<Project>> GetProjectsAsync()
{
    using (Context ctx= new ProjectContext())
    {
        IEnumerable<Project> myProjects = ctx.Projects;
        return await myProjects.ToListAsync();
    }
}

编辑2: 我目前通过Concurrency in C# Cookbook获得了这本书Stephen Cleary,我正在寻找本书中的合适解决方案,并结合给定的建议。任何人都可以指出本书的某些部分可以帮助我完成我的场景,即从许多表中加载大量数据,这些数据将由应用程序利用吗?

编辑3:

// *****选项3 *****

// Constructor
public SomeViewModel()
{
    _service = service;
    DownloadData();
} 

// A normal method that awaits async methods
private void DownloadData()
{
    Task.Run(async () => await GetProjectDataAsync());
    Task.Run(async () => await GetAssignmentDataAsync());
    ... more await calls to async Task methods that call services that in turn have async Task methods
}

1 个答案:

答案 0 :(得分:4)

我怀疑其中任何一种都适合您的需求。由于构造函数不能async,因此无法等到您启动的任务完成。您可以调用Task.Wait,但这会消除异步所带来的所有好处,并且您需要处理由此产生的死锁。

现在,您开始执行的任务与其余的请求处理同时运行。这可能是活泼而不是你想要的。如果这有用的话,那是偶然的。

将该代码移出普通方法,并一直使用await