Entity Framework error: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

Another very long title for this one, and the result of a subtle bug I was experiencing.

I have a DotNetCore app, running Entity Framework Core, and I had a fairly simple controller as part of my API that just needed to add a new entry to a table, and it worked fine for the first call, but subsequent calls were generating this exception:

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

Here’s what the code looked like.

public async Task<bool> SaveNewItem([FromBody] Item item)
{
    var container = db.Containers.FirstOrDefaultAsync(
                c=>c.Id == item.ContainerId
                );
    if (container == null) return false;
    db.Items.Add(item);
    await db.SaveChangesAsync();
    return true;
}

This is a simplified example but it has the error.

As I said, the first call worked, and added the item to the table, but any subsequent call would throw the exception shown above.

It’s a subtle error, and one that the compiler or IDE doesn’t give any hints about. The culprit is the very first line, where I’m intending to look for a container entity to which the item should be added.

The bug is a missing ‘await’ before the FirstOrDefaultAsync call. This code will result in container having a task, rather than a container, and that task is never completed because it’s not awaited. It’s left hanging.

It’s an easy fix, though, just add the missing ‘await’ and everything works fine.

It’s a bit subtle, though.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s