#if UNITY
using System;
using System.Collections;
using UnityEngine;
namespace Foundation.Tasks
{
///
/// A task encapsulates future work that may be waited on.
/// - Support running actions in background threads
/// - Supports running coroutines with return results
/// - Use the WaitForRoutine method to wait for the task in a coroutine
///
///
///
/// var task = Task.Run(() =>
/// {
/// //Debug.Log does not work in
/// Debug.Log("Sleeping...");
/// Task.Delay(2000);
/// Debug.Log("Slept");
/// });
/// // wait for it
/// yield return task;
///
/// // check exceptions
/// if(task.IsFaulted)
/// Debug.LogException(task.Exception)
///
///
public class AsyncTask : AsyncTask
{
#region public fields
///
/// get the result of the task. Blocking. It is recommended you yield on the wait before accessing this value
///
public TResult Result;
#endregion
#region ctor
Func _function;
public AsyncTask()
{
}
///
/// Returns the task in the Success state.
///
///
public AsyncTask(TResult result)
: this()
{
Status = TaskStatus.Success;
Strategy = TaskStrategy.Custom;
Result = result;
}
///
/// Creates a new background Task strategy
///
///
public AsyncTask(Func function)
: this()
{
if (function == null)
throw new ArgumentNullException("function");
_function = function;
}
///
/// Creates a new task with a specific strategy
///
public AsyncTask(Func function, TaskStrategy mode)
: this()
{
if (function == null)
throw new ArgumentNullException("function");
if (mode == TaskStrategy.Coroutine)
throw new ArgumentException("Mode can not be coroutine");
_function = function;
Strategy = mode;
}
///
/// Creates a new Coroutine task
///
public AsyncTask(IEnumerator routine)
{
if (routine == null)
throw new ArgumentNullException("routine");
_routine = routine;
Strategy = TaskStrategy.Coroutine;
}
///
/// Creates a new Task in a Faulted state
///
///
public AsyncTask(Exception ex)
{
Exception = ex;
Strategy = TaskStrategy.Custom;
Status = TaskStatus.Faulted;
}
///
/// Creates a new task
///
public AsyncTask(TaskStrategy mode)
: this()
{
Strategy = mode;
}
#endregion
#region protected methods
///
/// Runs complete logic, for custom tasks
///
public override void Complete(Exception ex = null)
{
Result = default(TResult);
base.Complete(ex);
}
///
/// Runs complete logic, for custom tasks
///
public void Complete(TResult result)
{
Result = result;
base.Complete();
}
public override void Start()
{
Result = default(TResult);
base.Start();
}
protected override void Execute()
{
try
{
if (_function != null)
{
Result = _function();
}
Status = TaskStatus.Success;
OnTaskComplete();
}
catch (Exception ex)
{
Exception = ex;
Status = TaskStatus.Faulted;
if (LogErrors)
Debug.LogException(ex);
}
}
#endregion
}
}
#endif