async / await continuation

时间:2014-02-22 08:09:29

标签: c# asynchronous async-await

在下面的代码中,我需要并行执行三个Get ...方法。当Get ...方法完成时,我需要立即调用Save ...方法。注意保存...将事物作为参数。 在DoStuffAsync返回之前,必须完成所有Get和Save方法。

我的猜测是我需要继续Get ...方法,但我不知道如何构建它。

protected async void DoStuffAsync()
{
    SomeThing thing = new SomeThing { ID = 5 };
    SomeRepository rep = new SomeRepository();

    // We need to run all three Get... methods in parallel
    // As soon as a Get... method completes we need to save the result to the correct property on thing and call the Save... method .

    var getRed = rep.GetRedAsync().ContinueWith<Task<string>>(async x => { thing.Color1 = x.Result; await rep.SaveRedAsync(thing); return x; }); // does not compile
    var getBlue = rep.GetBlueAsync();
    var getGreen = rep.GetGreenAsync();

    string red = await getRed.Result; // this is not good because getBlue may finish before getRed.  We want dont want to wait on getRed before calling SaveBlue
    await rep.SaveRedAsync(thing);
    var b = await getBlue;  
    var c = await getGreen;

    // thing must be fully initialized before DoStuffAsync returns

    }


public class SomeThing
{
    public int ID { get; set; }
    public string Color1 { get; set; }
    public string Color2 { get; set; }
    public string Color3 { get; set; }
}

public class SomeRepository
{
    public async Task<string> GetRedAsync()
    {
        return await Task.Run(() => "red");
    }

    public async Task<string> GetBlueAsync()
    {
        return await Task.Run(() => "blue");
    }

    public async Task<string> GetGreenAsync()
    {
        return await Task.Run(() => "green");
    }

    public async Task SaveRedAsync(SomeThing thing)
    {
        // We need thing.ID here as well as other properties
        await Task.Delay(1);
    }

    public async Task SaveBlueAsync(SomeThing thing)
    {
        await Task.Delay(1);
    }

    public async Task SaveGreenAsync(SomeThing thing)
    {
        await Task.Delay(1);
    }
}

3 个答案:

答案 0 :(得分:7)

好吧,你可以明确使用ContinueWith - 或者你可以将每个“get and save”分解为单独的异步方法或async lambda。例如:

async Task GetAndSaveRedAsync(SomeThing thing, SomeRepository rep)
{
    var red = await rep.GetRedAsync();
    thing.Red = red;
    await SaveRedAsync(red);
    // Return red if you want (change the return type to Task<string>)
}

// Ditto for the others

然后:

protected async void DoStuffAsync()
{
    SomeThing thing = new SomeThing { ID = 5 };
    SomeRepository rep = new SomeRepository();

    var handleRed = GetAndSaveRedAsync(thing, rep);
    var handleBlue = GetAndSaveBlueAsync(thing, rep);
    var handleYellow = GetAndSaveYellowAsync(thing, rep);

    // Or use Task.WhenAll
    await handleRed;
    await handleBlue;
    await handleYellow;
}

答案 1 :(得分:7)

我不会混用ContinueWithawait而是直接使用async lambda:

protected async Task  DoStuffAsync()
{
    SomeThing thing = new SomeThing { ID = 5 };
    SomeRepository rep = new SomeRepository();

    // We need to run all three Get... methods in parallel
    // As soon as a Get... method completes we need to save the result to the correct property on thing and call the Save... method .

    Func<Task<X>> getRedFunc = async() =>
    {
        var result = await rep.GetRedAsync();
        thing.Color1 = result;
        await rep.SaveRedAsync(thing);
        return result;
    };

    var getRed = getRedFunc();

    var getBlue = rep.GetBlueAsync();
    var getGreen = rep.GetGreenAsync();

    await Task.WhenAll(getRed, getBlue, getGreen);
}

此外,除了事件处理程序之外,不要使用async void方法。您将无法观察此类方法的完成情况或处理可能引发的异常。

答案 2 :(得分:-1)

您可以尝试并行框架:

using System.Threading;

using System.Threading.Tasks;

Func<Task<string>>[] functions = { rep.GetRedAsync, rep.GetBlueAsync, rep.GetGreenAsync }; 
Var[] GetArray = new Var[functions.Length]
int i=0;
Parallel.ForEach (var function in functions)  
{  
             GetArray[i++]=function();

}  

注意:需要.Net 4