2015-05-08 08:09:28 +00:00
|
|
|
|
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-05-08 08:09:28 +00:00
|
|
|
|
{
|
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()
|
2015-05-08 08:09:28 +00:00
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void RunAsync_ActionThread(object info)
|
|
|
|
|
{
|
2015-06-10 08:49:43 +00:00
|
|
|
|
Task taskInfo = (Task)info;
|
2015-05-08 08:09:28 +00:00
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2015-06-10 08:49:43 +00:00
|
|
|
|
taskInfo.action();
|
2015-05-08 08:09:28 +00:00
|
|
|
|
taskInfo.Success = true;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2015-06-10 08:49:43 +00:00
|
|
|
|
taskInfo.thrownException = ex;
|
2015-05-08 08:09:28 +00:00
|
|
|
|
taskInfo.Success = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-06-10 08:49:43 +00:00
|
|
|
|
public static Task RunAsync(Action action)
|
2015-05-08 08:09:28 +00:00
|
|
|
|
{
|
|
|
|
|
// 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-05-08 08:09:28 +00:00
|
|
|
|
|
2015-06-10 08:49:43 +00:00
|
|
|
|
public static IEnumerable Await(Action action)
|
|
|
|
|
{
|
|
|
|
|
return Task.RunAsync(action).Await();
|
|
|
|
|
}
|
2015-05-08 08:09:28 +00:00
|
|
|
|
|
2015-06-10 08:49:43 +00:00
|
|
|
|
public IEnumerable Await()
|
|
|
|
|
{
|
2015-05-08 08:09:28 +00:00
|
|
|
|
// 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);
|
2015-05-08 08:09:28 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|