TListener
This is a functional listener provider library. You can instantiate a listener and listen a function.
這是一個函數式的監聽器類庫。可以通過實例化一個監聽器用於監聽一個函數體。
GitHub:https://github.com/mykge/TListener
Sample 例子
public class Program { public static void Main(string[] args) { var lastDate = DateTime.Now; var listener = new TListener.Listener<string>() .Listen(x => /*匿名參數是一個ListenerContext對象*/ { return true; /*監聽器將循環執行此函數,直到函數體返回true,則跳轉至Success中的函數體*/ }) .Success(x => { x.SyncContext /*SyncContext可以用於向主線程發送函數體*/ .Post(s => { Console.WriteLine(DateTime.Now.ToString()); /*Post中的操作會切換到主線程執行*/ }, null); }) .Log(x => Console.WriteLine("Log - Times : " + x.Counter.Count().ToString())) /*監聽函數體每次執行都將在函數最后執行Log函數體*/ .Exit(x => Console.WriteLine("Exit"))/*當監聽器結束監聽時,運行此函數體*/ .Interval(5000)/*監聽器執行監聽函數體的間隔*/ .Times(5, x => Console.WriteLine("Times Out"))/*監聽器Success函數得次數,並在次數達到后執行函數體*/ .Build();/*構建監聽器,在開始監聽前必須先構建監聽器*/ listener.Start();/*開始監聽*/ Console.ReadKey(); } }
Api Document
IListener
Methods
Listen
IListener<TModel> Listen(Func<ListenerContext<TModel>, bool> _handler)
設置監聽操作,當函數返回true則執行Success,如果拋出異常則執行Error.
參數
_handler :監聽函數體
Success
IListener<TModel> Success(Action<ListenerContext<TModel>> _handler)
當監聽函數返回true時,執行此函數體.
參數
_handler :函數體
Error
IListener<TModel> Error(Action<ListenerContext<TModel>, Exception> _handler)
當監聽函數拋出異常時,執行此函數體.
參數
_handler :異常處理函數體
Log
IListener<TModel> Log(Action<ListenerContext<TModel>> _handler)
每當執行監聽函數后,執行此函數.
參數
_handler :日志函數體
Interval
IListener<TModel> Interval(int _interval)
當執行監聽函數后,線程將掛起一段時間.
參數
_interval :線程掛起的時間
Times
IListener<TModel> Times(int times, Action<ListenerContext<TModel>>? _handler);
設置一個值,指示Success函數執行的最大次數.
參數
times :Success函數執行的最大次數.
?_handler :當Success函數執行次數達到最大次數時,執行此函數.
Exit
IListener<TModel> Exit(Action<ListenerContext<TModel>> _handler)
當監聽器退出時,執行此函數體.
參數
_handler :函數體
Build
IListener<TModel> Build()
構建監聽器,必須先構建監聽器才能啟動.
Start
void Start()
啟動監聽器.
Stop
void Stop()
停止監聽器.
ListenerContext 監聽器上下文類
Properties 屬性
SyncContext
SynchronizationContext SyncContext
提供線程通信的能力。詳情可以參照MSDN : SynchronizationContext Class
IsRunning
bool IsRunning
獲取或設置監聽器的運行狀態, RequestStop函數實際就是修改這個屬性的值.
TempData
Hashtable TempData
這個哈希表可以在一次監聽過程中的不同函數體間傳遞數據,其生命周期會在下一次執行監聽函數前被重置.
WorkThread
Thread WorkThread
負責執行整個監聽過程的工作線程.
Counter
ICounter Counter
計數器.
ListenerContext<>.Model
TModel ListenerContext<TModel>.Model
此屬性只在ListenerContext的泛型類中存在,用於表示TModel的實例對象.
Methods 方法
RequestStop
void RequestStop()
修改 IsRunning 的值為 false, 並等待工作線程退出.