123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- 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<string>, List<State>> funcGetStates,List<string> allkeys)
- {
- this.Keys = new List<string>();
- this.CommonKeys = new List<string>();
- this.States = new Dictionary<string, State>();
- 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<string> summarykeys = new List<string>();
- 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<State> 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;
- }
- }
- );
- });
- }
- /// <summary>
- /// Register keys for each page or common page
- /// </summary>
- /// <param name="keys"></param>
- /// <param name="isCommon"></param>
- public void Register(List<string> 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);
- }
- }
- }
- /// <summary>
- ///remove a page's key
- /// </summary>
- /// <param name="keys"></param>
- public void UnRegister(List<string> keys)
- {
- lock(lockObj)
- {
- this.Keys.Clear();
- }
- }
- public Dictionary<string, State> States { get; private set; }
- public MsgPool looper { get; private set; }
- private List<string> Keys { get; set; }
- private List<string> CommonKeys { get; set; }
- private Func<List<string>, List<State>> GetStates;
- private static object lockObj = new object();
- }
- }
|