EF and Async - Weird live scenario

2019-06-14 05:03发布

I'm implementing async all over my cloud-based project.

I'm now trying to figure out why my TransactionScope keeps crashing randomly. The messages are "Cannot perform this operation because there are pending operations" or "The operation is not valid for the state of the transaction" an other similar.
I say that it crashes randomly, because if you retry the operation, it works eventually...

At first I implemented the TransactionScopeAsyncFlowOption.Enabled overload... the fail ratio decreased.
Then I made the whole operation use the same DbContext (previous guys created a new one for each CRUD operation, like selecting a user? new context for you! now you want the sales of that user? let me get that using a new context! Create a new sale? Lets do that on this new context here... and so on...). fail ratio declined even further.
Then i decided to await as soon as possible (previously i was firing some queries at the start of the operation, and only waiting right before using the result). That significantly improved the fail ratio.

Now, I got a message in my logs that signaled a FK mismatch... Thats really weird because this is a very solid app and FK logic going wrong is a very basic mistake. Looking at the log, i see something like "Error for client CLIENT_A. Complete message: (bla bla bla) The conflict occurred in database db_CLIENT_B"!!!

In my multi-tenant app, each tenant has it's own database, so CLIENT_A should have problems only with db_CLIENT_A. We are very meticulous about this.

That is a really serious problem. That means that either unity container is giving the wrong instance of DbContext (it's configured for single instance per request) or there's a serious problem going on regarding the async/await and parallel and distinct operations... I think it could be mix, taking into account that DbContext is not thread-safe and neither is the Resolve, although it's getting called only once (resolve for DBContext happens very soon on the pipeline)

So my question is: What can i do to figure this out?

PS: ON the last 7 days, i have 5 logs for this. This might've happen more times (the switching) but if the other database has a compatible FK... well, i will here for that in a couple of days when managers start emitting financial reports...

1条回答
We Are One
2楼-- · 2019-06-14 05:34

This is caused by Unity. This happens when I call 'Resolve' within a async scope.

查看更多
登录 后发表回答