c# - Are expression trees thread-safe? -
i want cache expressions generated dynamically (with linqkit) in order pass them where
clause part of entity framework query.
so have like
private static expression<func<t, bool>> _expression; // gets value @ runtime public iqueryable<t> apply(iqueryable<t> query) { return query.where(_expression); // here _expression has value }
is safe multiple threads call apply
, execute queries in parallel? expression<tdelegate>
class thread-safe?
docs give standard "any public static (shared in visual basic) members of type thread safe..."
expression trees immutable. however, can refer things do change, e.g.
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); } } }
if expression tree refers things don't change, should fine. case in situations.
if expression tree does refer mutable state, if 1 thread mutates state, other threads applying expression tree may or may not see change, in normal way of memory models.
Comments
Post a Comment