using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace Xylem.Common.Utils.ProcessExec
{
///
/// Execution of process in separate task.
/// Task execution uses an initialization-, an execution-, an event-
/// and a finalization-routine.
/// Process states are given to successful-, erroneous- ore break-execution as a array of objects to keep it
/// anonymous.
///
public class ProcessExec
{
///
/// Definition of void thread call back function
///
public delegate void VoidCallbackFunction();
///
/// Definition of boolean thread call back function
///
public delegate Boolean BoolCallbackFunction();
///
/// Definition of thread call back function
///
/// execution of routine returned success
/// objects to callback function
public delegate void ExitStateCallbackFunction(Boolean success, Object[] obj);
///
/// Definition of thread call back function
///
private Object[] _exitObjects;
///
/// Current task calling the init-, the cyclic execution and the final-function.
/// The task adjusts the current culture.
///
/// initial function executed in caller task
/// execution function executed in separated new task
/// finalizing function
/// language selection passing
/// exit objects
///
/// - Initial.
///
public void NewProcess(VoidCallbackFunction initFn, BoolCallbackFunction execFn,
ExitStateCallbackFunction finalFn, CultureInfo cultureInfo, Object[] exitObjects)
{
_exitObjects = new Object[exitObjects.Length];
_exitObjects = exitObjects;
var success = false;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
initFn?.Invoke();
Task.Factory.StartNew(() =>
{
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
if (execFn == null) return;
success = (Boolean)execFn.DynamicInvoke();
}).ContinueWith(delegate { finalFn?.Invoke(success, _exitObjects); });
}
}
}