using BPASmartClient.Helper;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BPASmartClient.Bus.DataBus
{
///
/// 线程集中处理委托
///
///
public delegate void ActionKeyHandle(string action);
public delegate void ThreadExceptionHandle(string action, Exception ex);
public delegate void ThreadExitHandle(string action);
///
/// 执行器
///
public class Executer : Singleton
{
private System.Timers.Timer _timer4Monitor = new System.Timers.Timer(1000);
private ConcurrentDictionary _actions = new ConcurrentDictionary();
private object _async = new object();
public event ThreadExceptionHandle OnThreadException;
public event ThreadExitHandle ThreadExit;
///
/// 构造器
///
public Executer()
{
}
///
///
///
public void Dispose()
{
_timer4Monitor.Stop();
foreach (var th in _actions)
{
try { th.Value.Abort(); }
catch (ThreadAbortException) { }
}
}
///
///
///
///
public List GetActionInfos()
{
Monitor.TryEnter(_async, 200);
var actionInfos = _actions.Values.ToList();
Monitor.Exit(_async);
return actionInfos;
}
///
///
///
///
public void Abort(string key)
{
Monitor.TryEnter(_async, 200);
if (_actions.ContainsKey(key))
{
try { _actions[key].Abort(); }
catch (ThreadAbortException) { }
}
Monitor.Exit(_async);
}
///
///
///
///
///
public bool ContainsKey(string key)
{
Monitor.TryEnter(_async, 200);
var item = _actions[key];
Monitor.Exit(_async);
if (null != item)
{
return true;
}
return false;
}
///
///
///
///
///
///
///
public void Start(Action action, string name, bool isBackground = false, ThreadPriority priority = ThreadPriority.Normal)
{
Thread thread = new Thread(() =>
{
try
{
action();
ThreadExit?.Invoke(name);
}
catch (Exception ex)
{
OnThreadException?.Invoke(name, ex);
}
});
thread.IsBackground = isBackground;
thread.Priority = priority;
thread.Name = name;
thread.Start();
Monitor.TryEnter(_async, 50);
if (_actions.ContainsKey(name))
{
try { _actions[name].Abort(); }
catch (ThreadAbortException) { }
}
_actions[name] = thread;
Monitor.Exit(_async);
}
///
///
///
///
///
///
public bool StartWhiteReturn(Func action, int timeout = 3)
{
DateTime beginTime = DateTime.Now;
bool doResult = false;
while (DateTime.Now.Subtract(beginTime).TotalSeconds <= 3 && !doResult)
{
doResult = action();
}
return doResult;
}
///
///
///
public event ActionKeyHandle ActionAbort;
///
///
///
public event ActionKeyHandle ActionStarted;
}
}