尝试监视 Azure Batch 任务时获取 'This operation is forbidden on unbound objects'

Getting 'This operation is forbidden on unbound objects' when trying to monitor an Azure Batch task

我想在 Azure Batch 中执行一个简单的任务,等待它完成并获得结果:

using (var client = _CreateBatchClient())
{
    var monitor = client.Utilities.CreateTaskStateMonitor();

    var task = new CloudTask(Guid.NewGuid().ToString(), "echo hello world");
    await client.JobOperations.AddTaskAsync("Test", task);
    await monitor.WhenAll(new List<CloudTask> { task }, TaskState.Completed, _timeout);

    var result = task.ExecutionInformation.Result;
}

并且 WhenAsync 行抛出 System.InvalidOperationException: 'This operation is forbidden on unbound objects.'

这个消息很模糊,而我离 tutorial 不远。怎么了?

从这段代码看并不明显,但实际上Azure Batch在这里并不知道如何识别任务。作业包含任务,但任务没有引用它运行的作业。而且task Id也不是全局标识task,只需要在一个job中是唯一的即可。

这里大概就是"unbound objects"的意思。监视器只是不明白要看什么。实际上,如果 WhenAsync 行被注释,下一行会抛出类似的 InvalidOperationException: 'The property ExecutionInformation cannot be read while the object is in the Unbound state.'

所以正确的方法是通过作业引用任务:

using (var client = _CreateBatchClient())
{
    var monitor = client.Utilities.CreateTaskStateMonitor();

    var id = Guid.NewGuid().ToString();
    var taskToAdd = new CloudTask(id, "echo hello world");
    await client.JobOperations.AddTaskAsync("Test", taskToAdd);

    var taskToTrack = await client.JobOperations.GetTaskAsync("Test", id);
    await monitor.WhenAll(new List<CloudTask> { taskToTrack }, TaskState.Completed, _timeout);
}

比较:

而要获取结果信息,需要再次"find"job中的task,否则为null。