t1 / TFDContents / Assets / KinectScripts / Utilities / AsyncTask.cs @ 9
이력 | 보기 | 이력해설 | 다운로드 (1.29 KB)
| 1 |
using System; |
|---|---|
| 2 |
using System.Threading; |
| 3 |
using UnityEngine; |
| 4 |
|
| 5 |
public enum AsyncTaskState |
| 6 |
{
|
| 7 |
Running, Failed, Succeed |
| 8 |
} |
| 9 |
|
| 10 |
public class AsyncTask<T> |
| 11 |
{
|
| 12 |
public AsyncTaskState State { get; internal set; }
|
| 13 |
public bool LogErrors { get; set; }
|
| 14 |
public T Result { get { return _result; } }
|
| 15 |
public string ErrorMessage { get { return _errorMessage; } }
|
| 16 |
|
| 17 |
private Func<T> _action; |
| 18 |
private T _result; |
| 19 |
private string _errorMessage; |
| 20 |
|
| 21 |
|
| 22 |
public AsyncTask(Func<T> backgroundAction) |
| 23 |
{
|
| 24 |
this._action = backgroundAction; |
| 25 |
LogErrors = true; |
| 26 |
} |
| 27 |
|
| 28 |
public void Start() |
| 29 |
{
|
| 30 |
State = AsyncTaskState.Running; |
| 31 |
#if !NETFX_CORE |
| 32 |
ThreadPool.QueueUserWorkItem(state => DoInBackground()); |
| 33 |
#else |
| 34 |
System.Threading.Tasks.Task.Run(() => DoInBackground()); |
| 35 |
#endif |
| 36 |
} |
| 37 |
|
| 38 |
private void DoInBackground() |
| 39 |
{
|
| 40 |
_result = default(T); |
| 41 |
_errorMessage = string.Empty; |
| 42 |
|
| 43 |
try |
| 44 |
{
|
| 45 |
if (_action != null) |
| 46 |
{
|
| 47 |
_result = _action(); |
| 48 |
} |
| 49 |
|
| 50 |
State = AsyncTaskState.Succeed; |
| 51 |
} |
| 52 |
catch (Exception ex) |
| 53 |
{
|
| 54 |
State = AsyncTaskState.Failed; |
| 55 |
_errorMessage = ex.Message; |
| 56 |
|
| 57 |
if (LogErrors) |
| 58 |
{
|
| 59 |
Debug.LogException(ex); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
} |