using System;
using System.Threading;
using System.Threading.Tasks;

namespace MWS.Library.Common
{
    public class Executer
	{
		public static void TryRunByAsyn(Action fun, bool skipException = true)
		{
			Executer.TryRunSkipExceptoin(delegate
			{
				fun.BeginInvoke(null, null);
			}, skipException);
		}

		public static void TryRunByThreadPool(Action fun, bool skipException = true)
		{
			ThreadPool.QueueUserWorkItem(delegate (object obj)
			{
				Executer.TryRunSkipExceptoin(fun, skipException);
			});
		}

		public static void TryRunByTask(Action fun, bool skipException = true)
		{
			Task task = Task.Factory.StartNew(delegate ()
			{
				Executer.TryRunSkipExceptoin(fun, skipException);
			});
		}

		public static void TryRunByThread(Action fun, bool skipException = true)
		{
			ThreadStart start = new ThreadStart(fun.Invoke);
			Thread thread = new Thread(start)
			{
				IsBackground = true
			};
			if (skipException)
			{
				try
				{
					thread.Start();
				}
				catch
				{
				}
			}
			else
			{
				thread.Start();
			}
		}

		public static void TryRunSkipExceptoin(Action fun, bool skipException = true)
		{
			if (skipException)
			{
				try
				{
					fun();
				}
				catch (Exception ex)
				{
					LogHelper.WriteLog(ex.Message, ex);
				}
			}
			else
			{
				fun();
			}
		}

		public static void TryRunLogExceptioin(Action fun, string message = "")
		{
			try
			{
				fun();
			}
			catch (Exception ex)
			{
				string text = string.Format("{0}，{1}错误详情：{2}", message, Environment.NewLine, ex.AllMessage());
				LogHelper.WriteLog(message, ex);
			}
		}

		public static void TryRunThrowExceptioin(Action fun, string message = "")
		{
			try
			{
				fun();
			}
			catch (Exception ex)
			{
				string message2 = string.Format("{0}，请尝试重新运行/重启程序，或者联系技术支持。{1}错误详情：{2}", message, Environment.NewLine, ex.AllMessage());
				throw new ApplicationException(message2, ex);
			}
		}
	}
}
