C# 在使用实体框架等待数据更改时,是否有更好的替代Thread.Sleep的方法?

C# 在使用实体框架等待数据更改时,是否有更好的替代Thread.Sleep的方法?,c#,multithreading,entity-framework,C#,Multithreading,Entity Framework,我有一个使用实体框架访问的数据库和一组需要在远程机器上执行的操作。机器通过更新数据库进行通信,否则不会返回报告。考虑到代码其余部分的体系结构,提供一些我可以钩住的事件将是困难的(尽管这将是理想的)。我尝试做的一个例子是: private enum Machines { SetA, SetB }; private void Action() { ExecuteWork(Machines.SetA); while (!IsWorkDone(Machines.SetA

我有一个使用实体框架访问的数据库和一组需要在远程机器上执行的操作。机器通过更新数据库进行通信,否则不会返回报告。考虑到代码其余部分的体系结构,提供一些我可以钩住的事件将是困难的(尽管这将是理想的)。我尝试做的一个例子是:

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.
}
如果限制是我们必须依赖数据库进行状态更新,那么有没有更好的方法推迟执行下一个操作直到第一个操作完成

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;
    }
}

我建议使用
async
await
Task
来完成此任务。无需做太多工作,您可以将
Action()
函数更改为:

private async Task Action() { ExecuteWork(Machines.SetA); while (!IsWorkDone(Machines.SetA)) { await Task.Delay(TimeSpan.FromMinutes(1)); } ExecuteWork(Machines.SetB); }
如果函数没有标记为
async Task
,而是简单地标记为
void
,您将使用
t等待t完成。wait()

实体框架不是一个数据库-它是一种可以访问数据库并从中获取数据的数据库访问技术。EF支持各种数据库,但它不是一个数据库itself@marc更正,谢谢。回答得很好,这正是我要找的。
//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;
}