首页 > 解决方案 > 重用正则表达式类以在多个线程中进行匹配

问题描述

此代码在 Web 应用程序环境中是否被视为线程安全?具体IsMobile功能?是否可以从控制器在高流量 Web 应用程序中调用它。

我在 MSDN 上读到 regex 类是线程安全的,但是从匹配项返回的集合可能会出现问题,所以我不确定这是否适用于我的用例。

static Regex rg = new Regex(@"(?:phone|windows\s+phone|ipod|blackberry|(?:android|bb\d+|meego|silk|googlebot) .+? mobile|palm|windows\s+ce|opera\ mini|avantgo|mobilesafari|docomo|KAIOS)");
private static bool IsMobile(string agent)
{
     
    var matchedAgents = rg.Matches(agent);

    if (matchedAgents.Count > 0)
        return true;

    return false;
}

标签: c#asp.net-corethread-safety

解决方案


推荐阅读