Beispiel #1
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            if (!_nested)
            {
                if (!_completed)
                {
                    try
                    {
                        if (_readOnly)
                        {
                            CommitInternals();
                        }
                        else
                        {
                            RollbackInternal();
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }

                    _completed = true;
                }

                _dbContexts.Dispose();
            }

            // Pop ourself from the ambient scope stack
            var currentAmbientScope = AmbientScope.GetAmbientScope();

            if (currentAmbientScope != this) // This is a serious programming error. Worth throwing here.
            {
                throw new InvalidOperationException("DbContextScope instances must be disposed of in the order in which they were created!");
            }

            AmbientScope.RemoveAmbientScope();

            if (_parentScope != null)
            {
                if (_parentScope._disposed)
                {
                    var message = @"PROGRAMMING ERROR - When attempting to dispose a DbContextScope, we found that our parent DbContextScope has already been disposed! This means that someone started a parallel flow of execution (e.g. created a TPL task, created a thread or enqueued a work item on the ThreadPool) within the context of a DbContextScope without suppressing the ambient context first. 

In order to fix this:
1) Look at the stack trace below - this is the stack trace of the parallel task in question.
2) Find out where this parallel task was created.
3) Change the code so that the ambient context is suppressed before the parallel task is created. You can do this with IDbContextScopeFactory.SuppressAmbientContext() (wrap the parallel task creation code block in this). 

Stack Trace:
" + Environment.StackTrace;

                    System.Diagnostics.Debug.WriteLine(message);
                }
                else
                {
                    AmbientScope.SetAmbientScope(_parentScope);
                }
            }

            _disposed = true;
        }