is thread switching possible during request processing?

一曲冷凌霜 提交于 2019-12-08 05:43:56

问题


I have an MVC application, which also uses EF and a simple Unit of work pattern implementation. Here's what my UnitOfWork looks like:

public class UnitOfWork : IUnitOfWork
{
    [ThreadStatic]
    private static UnitOfWork _current;

    private MyContext _context;

    public static UnitOfWork Current
    {
        get { return _current; }
    }

    public UnitOfWork()
    {
         _current = this;
    }

    public MyContext GetContext()
    {
        if(_context == null)
            _context = new MyContext();

        return _context;
    }

    public int Commit()
    {
        return _context == null ? 0 : _context.SaveChanges();
    }

    public void Dispose()
    {
        _current = null;

        if(_context != null)
            _context.Dispose();
    }
}

I have a generic repository which encapsulates common db operations:

public class GenericRepository<TEntity, TEntityKey> where TEntity : class
{
    private MyContext _context;

    private MyContext Context
    {
        get { return _context ?? (_context = UnitOfWork.Current.GetContext()); }
    }

    public void Add(TEntity newEntity)
    {
       _context.Set<TEntity>().Add(newEntity);
    }

    //Other methods...
}

How it is used:

using(var unitOfWork = _unitOfWorkFactory.Create())
{
    _repository.Add(newEntity);
    unitOfWork.Commit();
}

So, the question is if it is possible, that the MVC framework internally switches threads while processing a request. Since the current UnitOfWork is thread static, such a switch will cause a NullReferenceException when calling UnitOfWork.Current (please correct if I'm not right).

来源:https://stackoverflow.com/questions/21067521/is-thread-switching-possible-during-request-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!