using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DigitalSchoolApi.App_Data
{
    public class TimeOutCheckTool
    {
        public T TimeoutCheck<T>(int ms, Func<T> func)
        {
            var wait = new ManualResetEvent(false);
            bool RunOK = false;
            var task = Task.Run<T>(() =>
            {
                var result = func.Invoke();
                RunOK = true;
                wait.Set();
                return result;
            });
            wait.WaitOne(ms);
            if (RunOK)
            {
                return task.Result;
            }
            else
            {
                return default(T);
            }
        }

        public bool TimeoutCheckTwo<Boolean>(int ms, Func<Boolean> func)
        {
            var wait = new ManualResetEvent(false);
            bool RunOK = false;
            var task = Task.Run<Boolean>(() =>
            {
                var result = func.Invoke();
                RunOK = true;
                wait.Set();
                return result;
            });
            wait.WaitOne(ms);
            if (RunOK)
            {
                return Convert.ToBoolean(task.Result);
            }
            else
            {
                return true;
            }
        }
    }
}
