c# – 在.NET中是否保持异步调用的顺序?用异步等待实现Logger?

我正在尝试创建一个简单的异步记录器.使日志记录调用非阻塞和尽可能不引人注目的想法.请考虑以下简化代码 –

class Logger {
    public async void Log(string message) {
        LogTable log = new LogTable(); //LogTable is an SqlServer table
        log.Timestamp = DateTime.Now;
        log.Message = message;
        log.SomeProp = SomeVariableTimeCalculation();
        var db = new Entities(); //db is an EF6 context
        db.Entry(log).State = EntityState.Added;
        db.LogTables.Add(log);
        await db.SaveChangesAsync();
   }
}    

可以按如下方式使用它(不等待任何Log(…)调用) –

class Account
    private readonly Logger logger = new Logger();
    public void CreateAccount(Account acc) {
        logger.Log("CreateAccount Start");
        //Maybe some async operations here
        logger.Log("CreateAccount Validation Start");
        bool isValid = Validate(acc);
        logger.Log("CreateAccount Validation End");
        if(isValid) {
            logger.Log("CreateAccount Save Start");
            acc.Save();
            logger.Log("CreateAccount Save End");
        }
        else {
            logger.Log("Account validation failed");
        }
        logger.Log("CreateAccount End");
    }
}

我的问题是 –

>一个接一个地有多个异步Log(…)调用.编译器是否可以选择同时并行运行所有它们?如果是,编译器是否知道维护这些调用的顺序以便logger.Log(“CreateAccount Validation Start”);在logger.Log之前没有结束运行(“CreateAccount Start”);?
>如果编译器没有保留顺序,那么除了在Logger类中维护队列之外,还有其他办法吗?

更新:澄清 – 我主要担心的是避免竞争条件,例如,导致logger.Log(“CreateAccount Validation Start”);在logger.Log之前运行/完成(“CreateAccount Start”);并在不阻止CreateAccount的情况下调用Log.

最佳答案

Can the compiler potentially choose to run all them in parallel simultaneously?

不.异步与并行完全不同.

If the compiler doesn’t preserve order, then is there a way around it other than maintaining a queue within the Logger class?

编译器确实保留了顺序(即,await用于顺序异步代码).但是,队列仍然不是一个坏主意,因为您可能不希望在每次日志记录调用时都访问实际数据库.

点赞