Is asynchronous call order supported in .NET? Logger implementation with asynchronous wait?

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(); //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();
   }
}    

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");
        //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");
    }
}

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.

+4
3

, ?

. parallelism.

, , Logger?

(.. await ). , , , , .

+2

// parallelism, async , await 1.

, Log , , , , SaveChangesAsync.


1 , , . , , .

0

, , , , 1, 2, 3,..., 999, 1000

for (int i = 1; i <= 1000; ++i)
{
    logger.Log(i.ToString());
}

- . , , , , , 5 4.

0

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


All Articles