Is there a better alternative to Thread.Sleep when waiting for data to change using the Entity Framework?

I have a database that I am accessing using the Entity Framework and a set of actions that I need to perform in order on the remote machines. Machines exchange data when they are executed by updating the database and do not report otherwise. Given the architecture of the rest of the code, providing some event that I can connect to would be difficult (although that would be ideal). An example of what I'm trying to do is:

private enum Machines
{
    SetA,
    SetB
};

private void Action()
{
    ExecuteWork(Machines.SetA);
    while (!IsWorkDone(Machines.SetA))
    {
        Thread.Sleep(TimeSpan.FromMinutes(1));
    }
    ExecuteWork(Machines.SetB);
}

private void ExecuteWork(Machines machineGroup)
{
    // Do long running work on every remote machine in this set, between 10-40 minutes.
    // When this work is completed, each machine reports its completion to a database.
}

Is there a better way to hold back the next action until the first action is completed if the limitation is that we must rely on the database to update the state in order to continue?

private bool IsWorkDone(Machines machineGroup)
{
    using (_context = new DbContext())
    {
        var machines = _context.Machines.Where(machine => machine.Group.Equals(machineGroup.ToString(), StringComparison.OrdinalIgnoreCase));
        foreach (var machine in machines)
        {
            if (machine.Status == Status.Incomplete)
            {
                return false;
            }
        }
        return true;
    }
}
+4
1

async, await Task . Action() :

private async Task Action()
{
    ExecuteWork(Machines.SetA);
    while (!IsWorkDone(Machines.SetA))
    {
        await Task.Delay(TimeSpan.FromMinutes(1));
    }
    ExecuteWork(Machines.SetB);
}

ExecuteWork(), . , , Action(), :

//does not have to be async
private async Task Test()
{
    //Action will execute until it hits the await Task.Delay(),
    //at which point, execution will return to this function
    //(if Test() is marked async) until the time span is up.
    Task t = Action();
    //If Test() is not async, I believe that Action() will run
    //on a separate thread, but I may be wrong.

    for(int i = 0; i < 100; i++){
        console.log(i);
    }

    //At this point, execution of Test() will stop until
    //Action() finnishes, and the calling function will continue if it 
    //has the async modifier.
    await t;
}

async Task, void, t, t.Wait().

+5

Source: https://habr.com/ru/post/1583904/


All Articles