目前我正在使用UnitOfWork存储库模式并更改了我的get调用,这样如果内存中没有存储查询,它将查询并使用MemoryCache将查询结果存储在内存中。在将其存储到内存缓存中时,我已经设置好了sql依赖项。
我当前的问题是,如果查询是在任务/后台线程中运行的,那么sql通知看起来并不是线程安全的,并且我没有向主UI线程返回通知。请问我该怎么做?如果SqlDependency不能在另一个线程中完成,有没有办法告诉主线程设置通知?
Sql Dependy Code来自在线项目,可以在https://code.msdn.microsoft.com/How-to-use-SqlDependency-5c0da0b3
找到人员存储库代码
private static readonly List<ImmediateNotificationRegister<Person>> NotificationRegisters =
new List<ImmediateNotificationRegister<Person>>();
public PersonRepository(ApplicationDbContext context)
: base(context)
{ }
public IEnumerable<Person> GetActive()
{
return Get(x => x.Active, o => o.OrderBy(x => x.CorrespondenceName));
}
public IEnumerable<Person> Get(
Expression<Func<Person, bool>> filter = null,
Func<IQueryable<Person>, IOrderedQueryable<Person>> orderBy = null,
int? numberOfEntities = null,
IEnumerable<string> includeProperties = null, bool useCache = false)
{
IQueryable<Person> query = DbSet;
List<Person> result;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
query = orderBy(query);
}
var actualNumberOfEntities = int.MaxValue;
if (numberOfEntities.HasValue)
{
actualNumberOfEntities = Math.Max(1, numberOfEntities.Value);
}
if (!useCache)
{
if (includeProperties != null)
{
query = includeProperties.Aggregate(query,
(current, includeProperty) => current.Include(includeProperty));
}
return query.AsExpandable().Take(actualNumberOfEntities).ToList();
}
if (MemoryCache.Default[query.ToString()] == null)
{
var notification = new ImmediateNotificationRegister<Person>(Context, query);
notification.OnChanged += NotificationOnChanged;
NotificationRegisters.Add(notification);
if (includeProperties != null)
{
query = includeProperties.Aggregate(query,
(current, includeProperty) => current.Include(includeProperty));
}
result = query.AsExpandable().Take(actualNumberOfEntities).ToList();
MemoryCache.Default[query.ToString()] = result;
return result;
}
return ((IEnumerable<Person>)MemoryCache.Default[query.ToString()]).ToList();
}