我想缓存一些动态生成的表达式(使用LinqKit),以便将它们传递给Where作为Entity Framework查询一部分的子句.
所以我有类似的东西
private static Expression<Func<T, bool>> _expression; // Gets a value at runtime
public IQueryable<T> Apply(IQueryable<T> query)
{
return query.Where(_expression); // Here _expression already has a value
}
Run Code Online (Sandbox Code Playgroud)
多线程调用Apply然后并行执行这些查询是否安全?是Expression<TDelegate>类线程安全的?
Docs只提供标准"此类型的任何公共静态(在Visual Basic中共享)成员都是线程安全的......"
Jon*_*eet 14
表达树本身是不可变的.但是,他们可以参考那些确实发生变化的事情,例如
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
public class Test
{
static void Main()
{
int multiplier = 3;
IQueryable<int> values = new List<int> { 1, 2 }.AsQueryable();
Expression<Func<int, int>> expression = x => x * multiplier;
// Prints 3, 6
foreach (var item in values.Select(expression))
{
Console.WriteLine(item);
}
multiplier = 5;
// Prints 5, 10
foreach (var item in values.Select(expression))
{
Console.WriteLine(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的表达式树只引用不改变的东西,它应该没问题.大多数情况都是如此.
如果表达式树确实引用了可变状态,那么如果一个线程改变了该状态,则应用表达式树的其他线程可能会或可能不会以内存模型的正常方式看到更改.
| 归档时间: |
|
| 查看次数: |
397 次 |
| 最近记录: |