city-generation/Game/Assets/Scripts/Utils/Task.cs

71 lines
1.7 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TransportGame.Utils
{
2015-06-10 08:49:43 +00:00
public class Task
{
2015-06-10 08:49:43 +00:00
public bool? Success { get; private set; }
private Exception thrownException;
private Action action;
private Thread thread;
private Task()
{
}
private static void RunAsync_ActionThread(object info)
{
2015-06-10 08:49:43 +00:00
Task taskInfo = (Task)info;
try
{
2015-06-10 08:49:43 +00:00
taskInfo.action();
taskInfo.Success = true;
}
catch (Exception ex)
{
2015-06-10 08:49:43 +00:00
taskInfo.thrownException = ex;
taskInfo.Success = false;
}
}
2015-06-10 08:49:43 +00:00
public static Task RunAsync(Action action)
{
// Set up task info object
2015-06-10 08:49:43 +00:00
Task taskInfo = new Task();
taskInfo.action = action;
taskInfo.thread = new Thread(RunAsync_ActionThread);
// Start thread
taskInfo.thread.Start(taskInfo);
// Return task info
return taskInfo;
}
2015-06-10 08:49:43 +00:00
public static IEnumerable Await(Action action)
{
return Task.RunAsync(action).Await();
}
2015-06-10 08:49:43 +00:00
public IEnumerable Await()
{
// Wait for thread to finish
while (thread.ThreadState == ThreadState.Running)
yield return null;
thread.Join();
// Rethrow exception
2015-06-10 08:49:43 +00:00
if (Success.HasValue && !Success.Value)
throw new Exception("Task failed", thrownException);
}
}
}