一项作业经常会依赖另一项作业的结果。例如,作业 A 可能会对作业 B 用作输入的 NativeArray 进行写入。在调度相关作业时,必须将此类依赖关系告知作业系统。在所依赖的作业完成前,作业系统不会运行存在依赖的作业。一项作业可以依赖多项作业。
另外还存在作业链,作业链中的每项作业都依赖于上一项作业。但依赖关系会延迟作业的执行,因为必须等到依赖项完成后才能运行作业。要完成一项存在依赖关系的作业,必须首先完成其依赖的所有作业,以及这些作业所依赖的作业。
调用作业的 Schedule 方法时,它会返回 JobHandle。您可以使用 JobHandle 作为其他作业的依赖项。如果一项作业依赖另一项作业的结果,则可以将第一项作业的 JobHandle 作为参数传递给第二项作业的 Schedule 方法,如下所示:
JobHandle firstJobHandle = firstJob.Schedule();
secondJob.Schedule(firstJobHandle);
如果某项作业存在许多依赖项,那么您可以使用 JobHandle.CombineDependencies 方法来将它们合并。CombineDependencies 让您能将依赖项传递给 Schedule 方法。
NativeArray<JobHandle> handles = new NativeArray<JobHandle>(numJobs, Allocator.TempJob);
// Populate `handles` with `JobHandles` from multiple scheduled jobs...
JobHandle jh = JobHandle.CombineDependencies(handles);
以下是具有复数依赖项的多个作业的示例。最佳做法是将作业代码(MyJob 和 AddOneJob)放在与 Update 和 LateUpdate 代码分开的文件中,但为了清晰起见,示例使用了单个文件:
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
public class MyDependentJob : MonoBehaviour
{
// Create a native array of a single float to store the result. This example waits for the job to complete.
NativeArray<float> result;
// Create a JobHandle to access the results
JobHandle secondHandle;
// Set up the first job
public struct MyJob : IJob
{
public float a;
public float b;
public NativeArray<float> result;
public void Execute()
{
result[0] = a + b;
}
}
// Set up the second job, which adds one to a value
public struct AddOneJob : IJob
{
public NativeArray<float> result;
public void Execute()
{
result[0] = result[0] + 1;
}
}
// Update is called once per frame
void Update()
{
// Set up the job data for the first job
result = new NativeArray<float>(1, Allocator.TempJob);
MyJob jobData = new MyJob
{
a = 10,
b = 10,
result = result
};
// Schedule the first job
JobHandle firstHandle = jobData.Schedule();
// Setup the data for the second job
AddOneJob incJobData = new AddOneJob
{
result = result
};
// Schedule the second job
secondHandle = incJobData.Schedule(firstHandle);
}
private void LateUpdate()
{
// Sometime later in the frame, wait for the job to complete before accessing the results.
secondHandle.Complete();
// All copies of the NativeArray point to the same memory, you can access the result in "your" copy of the NativeArray
// float aPlusBPlusOne = result[0];
// Free the memory allocated by the result array
result.Dispose();
}
}