15. Wait for a job
Ore does not arrive the moment a golem starts mining. Write a spell that waits for the job to end, checks its result, then continues. async, await and Job.Wait unlock with your first Rebuild.
Separate acceptance from completion
An Ok result from Mine means the request was accepted. Mining still takes time. Accepted work runs as a job. Get it from Job, then use Wait to wait for it to end.
public class Program : ArcaneProgram
{
public async void OnStart()
{
var result = Workshop.Golems[0].Mine(Mineral.Ore, 20);
if (!result.Ok)
{
return;
}
var job = result.Job;
await job.Wait();
if (job.Status == JobStatus.Completed)
{
Workshop.Log.Write("Mining completed.");
}
}
}The first if checks acceptance. If !result.Ok is true, return ends OnStart before it accesses Job. Only an accepted request proceeds to the next line.
Pause at await and continue later
At await job.Wait();, the method pauses. When the wait ends, it continues to the following if statement. async allows the method to use await.
Cancellation or failure also ends the wait. The spell checks job.Status == JobStatus.Completed before displaying the completion message.
Wait for a duration
await Workshop.Clock.Delay(1.0); waits for one second of online time. A number with a decimal point, such as 1.0, can specify the duration. The allowed range is 0 to 86400 seconds. Delay alone does not tell you whether a job has finished.
Other event handlers do not run concurrently during a wait. Incoming OnTick events are reduced to the latest one.
What happens when you stop
Stopping the script discards the continuation from the waiting line. A normal resume calls OnStart from the beginning. Resuming after rejoining calls OnRestored, so it does not call this example's OnStart.
Accepted mining jobs continue while you are online. The script's wait and the job itself have separate lifetimes.
Exercise
A job is cancelled and Wait returns. Does this example display Mining completed.?
Show example solutionHide example solution
No. Execution reaches the next line, but Status is not Completed, so it skips the if block.
