我如何改善这个有效的sqldependency实现?

时间:2019-06-25 16:45:36

标签: c# asp.net-mvc singleton sqldependency

我是C#MVC的初学者(大约6个月的自学时间),目前在我的第一个项目上工作,最近遇到了用户刷新页面时SQL依赖项重复的问题。 通过查看跨站点的各种帖子和文章,我将一个可行的实现拼凑在一起,但是我仍然可以理解其中的一些元素,尤其是单例设计模式以及各种类和属性修饰符。 我想知道,我的代码中是否有任何漏洞,或者在我打算建立更多依赖关系时应该做的其他考虑?

要给项目规模提供一些背景知识,一次最多可使用500个用户,并且在繁忙期间,影响依赖关系的数据每秒大约更改一次。

非常感谢。 :)

这是我的依赖项类:

public sealed class UMCSingleton
{
    private static UMCSingleton instance;
    private static string connString = ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString;
    private static SqlConnection conn = new SqlConnection(connString);
    private SqlDependency dependency;
    private static volatile object padlock = new object();

    private UMCSingleton() {}

    public static UMCSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new UMCSingleton();
                    }
                }
            }

            return instance;
        }

    }

    public static SqlConnection getUMCConnection()
    {
        try
        {               
            if(conn == null)
            {
                conn = new SqlConnection(connString);
                conn.Open();
                return conn;
            }

            if(conn.State == ConnectionState.Closed)
            {
                conn.ConnectionString = connString;
                conn.Open();
            }                
        }
        catch (SqlException e) {}
        finally {}
        return conn;
    }

    public void RegisterUnmanagdCallDependency()
    {
        using (getUMCConnection())
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT [CallRef], [CallLoggedByUserId] FROM [dbo].[UnplannedCustomers] Where [ServiceFlowId] = 1";

                cmd.Notification = null;
                if (dependency == null || dependency.HasChanges == true)
                {
                    dependency = new SqlDependency(cmd);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                }

                using (SqlDataReader reader = cmd.ExecuteReader()) {}
            }
        }
    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e) //this will be called when any changes occur in db table. 
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SqlDependency dependency = (SqlDependency)sender;
            if (dependency.HasChanges == true)
            {
                dependency.OnChange -= dependency_OnChange;
            }
            UnmanagedCallHub.ShowCalls();

            RegisterUnmanagdCallDependency();
        }
    }
}

这是我的中心班级:

    public class UnmanagedCallHubData
{
    public string CallRef { get; set; }
    public string RaisedBy { get; set; }
}

public class UnmanagedCallHub : Hub
{
    private ApplicationDbContext _context;
    public UnmanagedCallHub()
    {
        _context = new ApplicationDbContext();
    }

    public static void ShowCalls()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<UnmanagedCallHub>();
        context.Clients.All.UpdateCalls();

    }
}

最后是我的api控制器:

    public class UnmanagedCallController : ApiController
{
    private ApplicationDbContext _context;
    private UserProfile _uPro;

    //CONSTRUCTOR SETS DB CONTEXT
    public UnmanagedCallController()
    {
        _context = new ApplicationDbContext();
        ApplicationUser user = HttpContext.Current.GetOwinContext()
            .GetUserManager<ApplicationUserManager>().FindById(HttpContext.Current.User.Identity.GetUserId());
        _uPro = _context.UserProfiles.SingleOrDefault(x => x.UserId == user.Id);
    }

    [HttpGet]
    [Authorize]
    public List<UnmanagedCallHubData> GetUnmanagedCalls()
    {
        List<UnmanagedCallHubData> calls = _context.UnplannedCustomers
            .Where(x => x.ServiceFlowId == 1)
            .Where(x => x.CurrentManagerUserId == null)
            .Select(x => new UnmanagedCallHubData
            {
                CallRef = x.CallRef,
                RaisedBy = x.CallLoggedByUserId
            }).ToList();


        UMCSingleton.Instance.RegisterUnmanagdCallDependency();


        return calls;
    }
}

0 个答案:

没有答案