using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common.DbExtends.Extends;
namespace Server.Services
{
///
/// 控制多线程任务等待帮助服务
///
public class WaitTaskThreadService
{
///
/// 等待
///
private List manualEvents = new List();
///
/// 启动任务
///
///
///
///
public void StartThread(string name, Action action, object stateObject)
{
var mre = new ManualResetEvent(false);
manualEvents.Add(mre);
var th = new Thread(o =>
{
var result = o as WaitTaskThreadObject;
try
{
result?.Action?.Invoke(result.StateObject);
}
catch (Exception e)
{
Client.SingleClient.Db.OnLog("处理任务" + name, e);
throw e;
}
finally
{
result?.ManualResetEvent.Set();
}
});
th.Name = name;
th.Start(new WaitTaskThreadObject()
{
Name = name,
StateObject = stateObject,
Action = action,
ManualResetEvent = mre
});
}
///
/// 启动任务
///
///
///
///
///
public void StartThread(string name, Action action, T stateObject = default)
{
StartThread(name, (o) =>
{
action?.Invoke((T)o);
}, (object)stateObject);
}
///
/// 启动任务
///
///
///
public void StartThread(string name, Action action)
{
StartThread(name, (o) =>
{
action?.Invoke();
}, null);
}
///
/// 等待全部任务完成
///
public void WaitAll()
{
WaitHandle.WaitAll(manualEvents.ToArray());
}
}
///
/// 线程启动参数数据
///
public class WaitTaskThreadObject
{
///
/// 线程名称,(调试用)
///
public string Name { get; set; }
///
/// 线程对象
///
public object StateObject { get; set; }
///
/// 执行具体方法
///
public Action Action { get; set; }
///
/// 线程同步事件
///
public ManualResetEvent ManualResetEvent { get; set; }
}
}