-
Notifications
You must be signed in to change notification settings - Fork 1
/
ThreadTask.cs
77 lines (69 loc) · 1.6 KB
/
ThreadTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* * * * * * * * * * * * * * * * * * * * * *
* Simple Multithreading in Unity
* callym 2015
* * * * * * * * * * * * * * * * * * * * * *
* Add this as a component on your object
*
* TODO:
* * optimise...
* * * * * * * * * * * * * * * * * * * * * */
using UnityEngine;
using System;
using System.Collections;
public class ThreadTask : MonoBehaviour
{
Func<object, object> calculate;
object input;
object results;
Action<object> callback;
bool done = false;
object handle = new object();
bool IsDone
{
get
{
bool tmp;
lock (handle)
{
tmp = done;
}
return tmp;
}
set
{
lock (handle)
{
done = value;
}
}
}
/// <summary>
/// Starts a task in a new thread, and runs a task in the main thread after it has finished.
/// </summary>
/// <param name="calculate">Function that will be run on the new thread.
/// Has to take in and return an object.</param>
/// <param name="callback">Function that is run in the main thread after the calculation has finished
/// Takes an object parameter (the results of the calculation). Returns void.</param>
/// <param name="o">An object that is passed to the calculation function.</param>
public void StartTask(Func<object, object> calculate, Action<object> callback, object o = null)
{
this.calculate = calculate;
this.callback = callback;
this.input = o;
ThreadTaskPool.QueueTask(this);
}
public void RunTask()
{
results = calculate(input);
IsDone = true;
}
public IEnumerator WaitForCallback()
{
while (!IsDone)
{
yield return null;
}
ThreadTaskPool.FinishTask(this);
callback(results);
}
}