-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ManagedJob.cs
79 lines (69 loc) · 2.6 KB
/
ManagedJob.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
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 managed object.
/// <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 ManagedJob : IJob, IDisposable
{
/// <summary>The managed job that this instance will forward job execution to.</summary>
/// <remarks>May be null.</remarks>
public IJob Job => _managedJobGcHandle.IsAllocated
? (IJob) _managedJobGcHandle.Target
: null;
/// <summary>Whether this instance has a managed job.</summary>
public bool HasJob => Job != null;
private GCHandle _managedJobGcHandle;
public ManagedJob(IJob managedJob)
{
_managedJobGcHandle = managedJob != null
? GCHandle.Alloc(managedJob)
: default;
}
/// <summary>Executes the managed job.</summary>
/// <remarks>If no managed job was passed, or the handle was already freed, this method is a no-op.</remarks>
public void Execute()
{
Job?.Execute();
}
/// <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 execution on a worker thread.</summary>
public JobHandle Schedule(JobHandle dependsOn = default)
{
var jobHandle = IJobExtensions.Schedule(this, dependsOn);
new DisposeJob<ManagedJob>(this).Schedule(jobHandle);
return jobHandle;
}
/// <summary>Perform the job's Execute method immediately on the same thread.</summary>
public void Run()
{
try
{
IJobExtensions.Run(this);
}
finally
{
Dispose();
}
}
#endregion
}
}