Skip to main content
 首页 » 编程设计

c#之在单独的线程中延迟编译 .NET 正则表达式

2024年01月28日26freeliver54

我一直在使用 C# 正则表达式,它在 Web 应用程序中被大量用作自定义模板系统的一部分。表达式很复杂,而且我注意到使用 Regex.Compiled 选项确实提高了性能。然而,编译的初始成本在开发过程中令人恼火,尤其是在迭代单元测试期间(提到了这种一般权衡 here )。

我目前正在尝试的一个解决方案是惰性正则表达式编译。我的想法是,通过在单独的线程中创建 Regex 的编译版本并在准备就绪时将其替换,我可以两全其美。

我的问题是:是否有任何理由说明这可能是一个糟糕的表现或其他原因?我问是因为我不确定跨线程分配诸如 jitting 和程序集加载之类的成本是否真的有效(尽管从我的基准测试来看它似乎有效)。 这是代码:

public class LazyCompiledRegex 
{ 
    private volatile Regex _regex; 
 
    public LazyCompiledRegex(string pattern, RegexOptions options) 
    { 
        if (options.HasFlag(RegexOptions.Compiled)) { throw new ArgumentException("Compiled should not be specified!"); } 
        this._regex = new Regex(pattern, options); 
        ThreadPool.QueueUserWorkItem(_ => 
        { 
            var compiled = new Regex(pattern, options | RegexOptions.Compiled); 
            // obviously, the count will never be null. However the point here is just to force an evaluation 
            // of the compiled regex so that the cost of loading and jitting the assembly is incurred here rather 
            // than on the thread doing real work 
            if (Equals(null, compiled.Matches("some random string").Count)) { throw new Exception("Should never get here"); } 
 
            Interlocked.Exchange(ref this._regex, compiled); 
        }); 
    } 
 
    public Regex Value { get { return this._regex; } } 
} 

请您参考如下方法:

听起来您想使用 Regex.CompileToAssembly作为编译时间步骤。