亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

asp.net中使用單例

標簽:
JavaScript

摘要

有这样一个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<string> Names;        public static SingleParameter CreateInstance()        {            if (instance == null)            {                lock (obj)                {                    if (instance == null)                    {                        instance = new SingleParameter();                    }                }            }            return instance;        }        private SingleParameter()        {            Names = new List<string>();        }        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<string> 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());        }    }}

复制代码

结果

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消