I am trying to create a simple asynchronous logger. The idea is to make journaling non-blocking and as unobtrusive as possible. Please consider the following simplified codes -
class Logger {
public async void Log(string message) {
LogTable log = new LogTable();
log.Timestamp = DateTime.Now;
log.Message = message;
log.SomeProp = SomeVariableTimeCalculation();
var db = new Entities();
db.Entry(log).State = EntityState.Added;
db.LogTables.Add(log);
await db.SaveChangesAsync();
}
}
It can be used as follows (without expecting a single log call (...)) -
class Account
private readonly Logger logger = new Logger();
public void CreateAccount(Account acc) {
logger.Log("CreateAccount Start");
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");
}
}
My questions -
There are several async calls Log(...)one by one. Can the compiler try to run all of them simultaneously in parallel? If so, does the compiler know to keep these calls in order so that it logger.Log("CreateAccount Validation Start");doesn't work before logger.Log("CreateAccount Start");?
If the compiler does not preserve order, is there a way around it other than maintaining a queue in the Logger class?
: . , , , , logger.Log("CreateAccount Validation Start"); / logger.Log("CreateAccount Start"); Log CreateAccount.