嵌套的异步任务

Joh*_*han 3 c# asp.net task-parallel-library

我想知道是否可以改进此代码以获得更好的性能.我是服务器端的整个异步的新手,所以请在这里忍受:

con.GetGame(id, game => {

    foreach(Player p in game.Team1)
    {
        p.SomeExtraDetails = GetPlayerDetails(p.Id);
    }

    // I would like the player data to be set on all players
    // before ending up here
});

private PlayerDetails GetPlayerDetails(double playerId)
{
    var task = con.GetPlayer(playerId);

    PlayerDetails ret = null;

    Task continuation = task.ContinueWith(t =>
    {
        ret = t.Result;
    });

    continuation.Wait();

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

如果我做对了,就continuation.Wait();阻止主线程.

有没有办法让任务同时运行?

Ree*_*sey 6

理想情况下,您可以使这些操作一直异步:

private Task<PlayerDetails> GetPlayerDetailsAsync(double playerId)
{
    return con.GetPlayer(playerId);
}

con.GetGame(id, game => {
    var tasks = game.Team1
                    .Select(p => new { Player=p, Details=GetPlayerDetailsAsync(p.Id)})
                    .ToList(); // Force all tasks to start...

    foreach(var t in tasks)
    {
        t.Player.SomeExtraDetails = await t.Details;
    }

    // all player data is now set on all players
});
Run Code Online (Sandbox Code Playgroud)

如果这不是一个选项(即:您没有使用VS 2012),您可以将代码简化为:

// This is a more efficient version of your existing code
private PlayerDetails GetPlayerDetails(double playerId)
{
    var task = con.GetPlayer(playerId);
    return task.Result;
}

con.GetGame(id, game => {
    // This will run all at once, but block until they're done
    Parallel.ForEach(game.Team1, p =>
    {
        p.SomeExtraDetails = GetPlayerDetails(p.Id);
    });

});
Run Code Online (Sandbox Code Playgroud)