0

I want to make use of the saveChangesAsync in a synchronous function. The situation I want to use this in is for example.

public string getName(int id)
{
 var db =  new dbContext();
 String name= db.names.find(id);
 db.log.add(new Log("accessed name");
 db.savechangesAsync();
 return name;
}

So basically I dont care when the log is actually saved to the database, I just dont want it to slow down my getName function. I want the getname to return and then the log can be saved to the database any time after / during that.

How would I go about achieving this? Nothing is dependant on the time that the log is submitted, So it can take 2 min for all I care.

I have come up with another solution:

    private async void UpdateLastComms(string _id)
    {
        int id = Int32.Parse(_id);
        using (var db = new dbContext())
        {
            db.Devices.Where(x => x.UserId == id).FirstOrDefault().LastComms = DateTime.Now;
            await db.SaveChangesAsync();
        }
    }

and I then can call this function like so UpdateLastComms("5");

How will the this compare to the first and will it execute as I think?

1 Answer 1

4

The problem with "fire and forget" methods like this is error handling. If there is an error saving the log to the database, is that something you want to know about?

If you want to silently ignore errors, then you can just ignore the returned task, as in your first example. Your second example uses async void, which is dangerous: if there is a database write error with your second example, the default behavior is to crash the application.

If you want to handle errors by taking some action, then put a try/catch around the body of the method in your second example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.