-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ManagedJobParallelFor.cs
81 lines (71 loc) · 2.91 KB
/
ManagedJobParallelFor.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
78
79
80
81
#if UNITY_2019_3_OR_NEWER
using System;
using System.Runtime.InteropServices;
using Unity.Jobs;
namespace Gilzoide.ManagedJobs
{
/// <summary>
/// A job structure that forwards execution to the managed job passed on its constructor.
/// The managed job may be of class types, as well as struct types with managed fields.
/// </summary>
/// <remarks>
/// It uses a <see cref="GCHandle"/> for accessing the list of managed objects.
/// <br/>
/// If you call <see cref="Schedule"/> or <see cref="Run"/>, the GCHandle will be freed automatically.
/// Otherwise, make sure to call <see cref="Dispose"/> when appropriate to free the internal object handle.
/// </remarks>
public struct ManagedJobParallelFor : IJobParallelFor, IDisposable
{
/// <summary>The managed job that this instance will forward job execution to.</summary>
/// <remarks>May be null.</remarks>
public IJobParallelFor Job => _managedJobGcHandle.IsAllocated
? (IJobParallelFor) _managedJobGcHandle.Target
: null;
/// <summary>Whether this instance has a managed job.</summary>
public bool HasJob => Job != null;
private GCHandle _managedJobGcHandle;
public ManagedJobParallelFor(IJobParallelFor managedJob)
{
_managedJobGcHandle = managedJob != null
? GCHandle.Alloc(managedJob)
: default;
}
/// <summary>Executes the managed job with a specific iteration index.</summary>
/// <remarks>If no managed job was passed, or the handle was already freed, this method is a no-op.</remarks>
public void Execute(int index)
{
Job?.Execute(index);
}
/// <summary>Frees the internal object GCHandle.</summary>
/// <remarks>If no managed job was passed, or the handle was already freed, this method is a no-op.</remarks>
public void Dispose()
{
if (_managedJobGcHandle.IsAllocated)
{
_managedJobGcHandle.Free();
}
}
#region Job scheduling/running
/// <summary>Schedule the job for concurrent execution on a number of worker threads.</summary>
public JobHandle Schedule(int arrayLength, int innerloopBatchCount, JobHandle dependsOn = default)
{
var jobHandle = IJobParallelForExtensions.Schedule(this, arrayLength, innerloopBatchCount, dependsOn);
new DisposeJob<ManagedJobParallelFor>(this).Schedule(jobHandle);
return jobHandle;
}
/// <summary>Perform the job's Execute method immediately on the main thread.</summary>
public void Run(int arrayLength)
{
try
{
IJobParallelForExtensions.Run(this, arrayLength);
}
finally
{
Dispose();
}
}
#endregion
}
}
#endif