How to avoid DbContext Issues in Multithread Scenario
<p>I'm working on a very big project, which is supposed to talk to a very old Command Base API, and perform lot of actions, which each of them must perform many commands to get to the point, and then I have to save the state of results.</p>

<p>Everybody talks to my DB, they add a record to my process queue, I read it, perform some action, return some results either in process queue itself or in a respected table.</p>

<p>The main pipeline is as the following image, I omit a lot of actions and locks.
    <a href="https://i.stack.imgur.com/vn70p.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vn70p.jpg" alt="enter code here"></a></p>

<p>DB is the EF DbContext, the black box, is action running in the main thread, which runs several actions and does this over and over till the application terminate.</p>

<p>The Orange Box, are the sub-thread who perform actions after they called by the main thread.</p>

<p>Previously I had 1 issue, where the DB went dead due to a transaction, but since must of the time I had 1 API in my queue or at most 2, and I only felt it under SQL management tools, I thought of fixing it later.</p>

<p>but newly, I felt the issue some time, but today I saw it,... I had a failed action, and then the application start to repeating the same process, over and over, without terminating it or doing any other, though it should return either success or error. so I trace it a little while and I notice it the failed spot (one of inner exception handler) which said I tried  to insert a duplicate key into the database, so I went and look at the Db changes, and I noticed that I have over five entry, which should only be one.</p>

<p>so I first thought of getting ride of changes before every <code>dB.SaveChange</code>, so I went over the web found some piece of code which renders all changes as unchanged.
so I start changing my application adding this piece of code:</p>

<pre><code>lock(DbAction){
  ClearingDbContextChanges();
  AddResults() if there is any
  Change() if there is any
  Delete() if there is any
  SetEntity as Modified if there is any
  Db.SaveChanges()
}
</code></pre>

<p>then before I run the application I reach to the last spot, where I notice that I can't use this action anymore, and it renders some of my main action unusable.</p>