C# 中的静态函数,并发问题

Static Functions in C#, Concurrency Problems

我的应用程序中有许多静态函数,它们在我的应用程序中被多次调用。随着用户数量的增加,这些功能可能会被多次调用。我只是想知道这些函数是否会产生任何并发问题。我的应用程序中的一些静态函数甚至与数据库交互。我确保大多数我的静态函数只使用局部变量。我的一些静态函数如下。 如果需要任何更改,请查看并提出建议。

public static bool ISValidString(string CheckString)
{
    if (CheckString != null)
        CheckString = CheckString.Trim();
    if (String.IsNullOrEmpty(CheckString) || String.IsNullOrWhiteSpace(CheckString) || CheckString == "-" ||
        CheckString == "NA" || CheckString == "." || CheckString == "--Select--" || CheckString == "0" || CheckString == "0.00" || CheckString == "00")
        return false;
    else
        return true;
}

    public static DataTable ProcessMaster(string Condition, string Master)
    {
        DataTable dt = new DataTable();
        dt = (((DataSet)HttpContext.Current.Application[Master]).Tables[0].Select(Condition).Length>0)
            ? ((DataSet)HttpContext.Current.Application[Master]).Tables[0].Select(Condition).CopyToDataTable()
            : ((DataSet)HttpContext.Current.Application[Master]).Tables[0].Clone();
        return dt;
    }


    private static void GetPayTypes()
    {
        HttpContext.Current.Application["PayTypeMaster"] = DBFactory.GetMasters(null, "GetPayTypes");
    }
    public static DataTable GetPayTypes(string Filter = null, bool ForceRefresh = false)
    {
        if (HttpContext.Current.Application["PayTypeMaster"] == null || ForceRefresh == true)
            GetPayTypes();

        string Condition;
        if (Factory.ISValidString(Filter))
            Condition = "PayTypeID like '%" + Filter + "%' or PayTypeDesc like '%" + Filter + "%'";
        else
            Condition = Filter;
        return Factory.ProcessMaster(Condition, "PayTypeMaster");
    }

    public static DataSet GetMasters(string Filter, string MasterName)
    {
        CompanyParams myparam = new CompanyParams();
        try
        {
            myparam.AddParameter("@TranType", MasterName);
            myparam.AddParameter("@Filter", Filter);
            return CompanyDB.GetData(SPNameMasters, myparam.Params);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {

        }
    }

为什么不在使用应用程序特定变量的代码周围使用 Monitor 或简单地锁定语句,并且不希望多个线程同时执行代码。最简单的互斥方式

正如@ranjit powar 所建议的,我在使用应用程序特定 variables/static 变量的代码周围使用 lock 语句解决了这个问题。请在下面找到程序。当您的函数完全使用局部变量时,您不需要这样做。

            static Object LockMulti = new Object();

            lock (LockMulti)
            {
              -- Application specific variables/Static Variables Code Here
            }

            private static void GetPayTypes()
            {
                lock (LockMulti)
                {
                  HttpContext.Current.Application["PayTypeMaster"] = DBFactory.GetMasters(null, "GetPayTypes");
                }
            }

此外,最好使用静态变量而不是 HttpContext.Current.Application 变量。两者都提供相同的功能,但是当您使用静态变量时有许多优点,例如易于调试、类型安全等,