Version: 6000.3
语言: 中文
创建和运行作业
并行作业

作业依赖关系

通常,一项工作取决于另一项工作的结果。例如,作业 A 可能会写入NativeArray作业 B 用作输入。在调度依赖作业时,必须将此类依赖关系告知作业系统。作业系统在它所依赖的作业完成之前不会运行依赖作业。一个作业可以依赖于多个作业。

您还可以拥有一系列作业,其中每个作业都依赖于前一个作业。但是,依赖项会延迟作业执行,因为您必须等待作业的任何依赖项完成才能运行。完成依赖作业必须首先完成它所依赖的任何作业,以及这些作业所依赖的任何作业。

当您调用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);

多个作业和依赖项的示例

下面是具有多个依赖项的多个作业的示例。最佳做法是将作业代码 (MyJobAddOneJob) 在单独的文件中将UpdateLateUpdate代码,但为了清楚起见,此示例是一个文件:

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();
    }

}

其他资源

创建和运行作业
并行作业