using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using System.Threading; using OpenSEMI.Core.Msg; namespace OpenSEMI.ClientBase.Handlers { public class StatesHandler : IHandler { public StatesHandler(Func, List> funcGetStates,List allkeys) { this.Keys = new List(); this.CommonKeys = new List(); this.States = new Dictionary(); this.looper = new MsgPool(500, Do); //define an external function to let client implement this.GetStates = funcGetStates; //init states list allkeys.ForEach(key => { this.States.Add(key, new State() { Key = key, DisplayValue = string.Empty }); }); } public void Handle() { this.looper.Run(); } public void Do(MsgPool pool) { List summarykeys = new List(); lock (lockObj) { if (this.CommonKeys.Count == 0 && this.Keys.Count == 0) return; if (Application.Current == null || Application.Current.Dispatcher == null) return; //common and current page keys if (this.CommonKeys.Count > 0) summarykeys.AddRange(this.CommonKeys); if (this.Keys.Count > 0) summarykeys.AddRange(this.Keys); } List states = GetStates(summarykeys); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate { if (states == null) return; states.ForEach( state => { if (this.States.ContainsKey(state.Key)) { this.States[state.Key].DisplayValue = state.DisplayValue; } } ); }); } /// /// Register keys for each page or common page /// /// /// public void Register(List keys, bool isCommon = false) { lock (lockObj) { if (isCommon) { keys.ForEach(e => { if (!this.CommonKeys.Contains(e)) this.CommonKeys.Add(e); }); } else { this.Keys.Clear(); this.Keys.AddRange(keys); } } } /// ///remove a page's key /// /// public void UnRegister(List keys) { lock(lockObj) { this.Keys.Clear(); } } public Dictionary States { get; private set; } public MsgPool looper { get; private set; } private List Keys { get; set; } private List CommonKeys { get; set; } private Func, List> GetStates; private static object lockObj = new object(); } }