嵌套异步/等待

时间:2018-01-17 05:31:39

标签: c# asp.net asynchronous async-await

如下所示,与async / await函数同时运行任务的最佳方式是什么:

private async void ProcessItem()
{
    while (true)
    {
        await this.FetchDeviceData(); //Read From Devices
        await Task.Delay(2000);   //300000
        await this.Process(); //Insert Into DataBase
    }
}

private async Task FetchDeviceData()
{
    await Task.Run(() =>
    {
        //Read From all Devices;
    }
} 

private async Task Process()
{
    if (!(await RDataBase.ProcessItem(Mem,Date)))
    //Update Record;
}

public static async Task<bool> ProcessItem(int Memb, int Date)
{
    return await Task.Run(() =>
    {
        try
        {
            //Array List = Read Device Info From DataBase
            return True;
        }
        catch
        {
            return false;
        }
    });
}

2 个答案:

答案 0 :(得分:0)

据我了解,您希望按某种顺序处理任务。看How to: Chain Multiple Tasks with Continuations

答案 1 :(得分:0)

如果你想并行完成所有三项操作,你应该使用Task.WhenAll。

from datetime import datetime, timedelta

Entry.objects.filter(pub_date__gte = datetime.now() - timedelta(days=1)) 

有关详细信息,请参阅this document发布。