摘要
有這樣一個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()); } } }
結果