-1

as follow ,what's the best way for Run Task simultaneously with async/await functions:

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;
        }
    });
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
bernova
  • 23
  • 1
  • 7
  • 1
    Could you please be more clear on what you are asking? As I can infer from your code, the `Delay` should run after the `FecthDeviceData` has completed its work and `Process` after the `Delay`. Isn't that true? If so, I don't get your question. Thanks – Christos Jan 17 '18 at 05:40
  • @Christos Tasks Should be run simultaneously – bernova Jan 17 '18 at 05:57
  • public static async Task ProcessItem(int Memb, int Date) { return await Task.Run(() => { try { return True; } catch { return false; } }); } – bernova Jan 17 '18 at 06:07
  • I don't get why you want to fetch data, execute an arbitrary delay, _and_ insert data into a database concurrently, especially if the data you're inserting in the database is related to the data you're fetching. But, whatever. You asked for it, you got it. See marked duplicate. – Peter Duniho Jan 17 '18 at 06:28

2 Answers2

0

As I understood you want to process tasks in some order. Look at How to: Chain Multiple Tasks with Continuations

Oleh V.
  • 11
  • 1
  • thanks , but as refere to [link](https://learn.microsoft.com/enus/dotnet/csharp/async) , i wrote my code using await/async functions – bernova Jan 17 '18 at 05:59
0

If you want to do all three operation in parallel you should use Task.WhenAll.

var task1 = this.FetchDeviceData(); //Read From Devices
var task2 = Task.Delay(2000);   //300000
var task3 = this.Process(); //Insert Into DataBase
await Task.WhenAll(new Task[]{task1,task2,task3 });

For More detail see this post.

madan
  • 445
  • 6
  • 16
  • I changed my code based of above , when Task.WhenAll is Finished? and is it true that use this code in While? – bernova Jan 17 '18 at 06:58