C# 在静态函数中使用new关键字创建对象时发生了什么

C# 在静态函数中使用new关键字创建对象时发生了什么,c#,singleton,C#,Singleton,这是我目前的代码: public class ServerUtility { public static int LogError(string source, string detail) { int iresult = -99; try { BaseRepository repo = new BaseRepository(); using (SqlConnection con =

这是我目前的代码:

public class ServerUtility
{
    public static int LogError(string source, string detail)
    {
        int iresult = -99;
        try
        {
            BaseRepository repo = new BaseRepository();
            using (SqlConnection con = new SqlConnection(repo.connectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand($"INSERT INTO [dbo].[LogError]([source],[detail],[date])VALUES('{source.Replace("'", "''")}','{detail.Replace("'", "''")}',GETDATE());SELECT @@IDENTITY", con))
                {
                    string getValue = cmd.ExecuteScalar().ToString();
                    iresult = Convert.ToInt32(getValue);
                } // command disposed here

            } //connection closed and disposed here
        }
        catch (Exception ex) { throw ex; }
        return iresult;
    }
}
我的问题是关于GetInstance方法:

BaseRepository repo = new BaseRepository();
using (SqlConnection con = new SqlConnection(repo.connectionString))
我总是在我的静态函数中将它设置为新对象,只是为了从AppSetting获取常量值

如果我将此代码实现到我的项目中,实际会发生什么? 演出怎么样

这是否会导致性能问题


谢谢

就像@gtosto提到的那样,您没有正确地实现单例

应该是:

    public static SenderBackupProvider GetInstance()
    {            
        if (oInstance == null)
        {
            oInstance = new SenderBackupProvider(CommFunction.GetLogNumber(CommonConst.APPID));
        }

        return oInstance;
    }
退房

编辑:

由于OP不认为第一次运行时,
oInstance
变量应该为空,所以这里有一个屏幕截图


仔细查看代码后,您使用的是web应用程序。静态变量的生命周期因平台而异。您可能需要在IIS中重新启动应用程序域。请参阅中的详细信息。

您的实现是错误的,您应该仅在oInstance为null时创建新的SenderBackupProvider实例,并且没有必要检查来自
new
的返回是否为null-它永远不会为null。我还想说,除非SenderBackupProvider的工作方式有些奇怪,否则您不需要担心性能,但是它是如何被设计来使用的。你可以选择几种在C#中实现单例模式的方法之一,通过看@DylanNicholson有不同的实现单例模式的方法,我给出了最简单的一种。为OP添加了一个引用链接。是的,这是我创建getInstance对象的方法,但是当我调试代码时,oInstance永远不会为null。这怎么会发生?然后,我需要在每个DB快照中分配lognumber。我已经将我的代码更改为:public static SenderBackupProvider GetInstance(){if(oInstance==null)oInstance=new SenderBackupProvider(CommFunction.GetLogNumber(CommonConst.APPID));else oInstance.LogNumber=CommFunction.GetLogNumber(CommonConst.APPID);if(oInstance==null){return oInstance;}else{return oInstance;}}@toha在第一次调用
SenderBackupProvider.GetInstance()之前,它一直为null
因为所有后续请求都将有一个实例,因为第一次实例化它之后,它将有一个实例。我说过,我以前实现过您的代码,但oInstance从不为null。我调试它,即使我第一次调用getInstance,它也不为null。