博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asp.net中使用单例
阅读量:6999 次
发布时间:2019-06-27

本文共 2440 字,大约阅读时间需要 8 分钟。

摘要

有这样一个service,需要运行的asp.net站点上,但要保证这个实例是唯一的。单例用来启用聊天机器人,保证唯一,以免启动多个,造成客户端发送消息的时候,会造成每个机器人都发送消息,app收到多条消息。

Demo

单例类

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Wolfy.SingleDemo.Models{    public class SingleParameter    {        private static SingleParameter instance;        private static readonly object obj = new object();        private static List
Names; public static SingleParameter CreateInstance() { if (instance == null) { lock (obj) { if (instance == null) { instance = new SingleParameter(); } } } return instance; } private SingleParameter() { Names = new List
(); } public void Remove(string name) { lock (obj) { for (int i = Names.Count - 1; i >= 0; i--) { if (Names[i] == name) { Names.RemoveAt(i); } } } } public void Set(string name) { lock (obj) { if (!Names.Contains(name)) { Names.Add(name); } } } public List
GetNames() { lock (obj) { return Names; } } }}

测试例子

在视图List中展示添加了哪些name,在视图Add中添加name,通过刷新list查看是否已经保存在了集合中。

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Wolfy.SingleDemo.Models;namespace Wolfy.SingleDemo.Controllers{    public class HomeController : Controller    {        // GET: Home        public ActionResult List()        {            SingleParameter single = SingleParameter.CreateInstance();            for (int i = 0; i < 10; i++)            {                single.Set((i + 1).ToString());            }            return View(single.GetNames());        }        public ActionResult Add(string name)        {            SingleParameter single = SingleParameter.CreateInstance();            single.Set(name);            return View(single.GetNames());        }    }}

结果

转载于:https://www.cnblogs.com/wolf-sun/p/5616239.html

你可能感兴趣的文章