57 lines
1.5 KiB
C#
57 lines
1.5 KiB
C#
|
using System;
|
|||
|
using System.Collections;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading;
|
|||
|
|
|||
|
namespace TransportGame.Utils
|
|||
|
{
|
|||
|
public static class Task
|
|||
|
{
|
|||
|
private class TaskInfo
|
|||
|
{
|
|||
|
public Action Action { get; set; }
|
|||
|
public bool? Success { get; set; }
|
|||
|
public Exception ThrownException { get; set; }
|
|||
|
}
|
|||
|
|
|||
|
private static void RunAsync_ActionThread(object info)
|
|||
|
{
|
|||
|
TaskInfo taskInfo = (TaskInfo)info;
|
|||
|
|
|||
|
try
|
|||
|
{
|
|||
|
taskInfo.Action();
|
|||
|
taskInfo.Success = true;
|
|||
|
}
|
|||
|
catch (Exception ex)
|
|||
|
{
|
|||
|
taskInfo.ThrownException = ex;
|
|||
|
taskInfo.Success = false;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public static IEnumerable RunAsync(Action action)
|
|||
|
{
|
|||
|
// Set up task info object
|
|||
|
TaskInfo taskInfo = new TaskInfo();
|
|||
|
taskInfo.Action = action;
|
|||
|
|
|||
|
// Start thread and wait
|
|||
|
var thread = new Thread(RunAsync_ActionThread);
|
|||
|
thread.Start(taskInfo);
|
|||
|
|
|||
|
// Wait for thread to finish
|
|||
|
while (thread.ThreadState == ThreadState.Running)
|
|||
|
yield return null;
|
|||
|
|
|||
|
thread.Join();
|
|||
|
|
|||
|
// Rethrow exception
|
|||
|
if (taskInfo.Success.HasValue && !taskInfo.Success.Value)
|
|||
|
throw new Exception("Task failed", taskInfo.ThrownException);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|