User guide
foreach (SpotInstanceRequest spotInstanceRequest in de
scribeResponse.DescribeSpotInstanceRequestsResult.SpotInstanceRequest)
{
// If the state is open, it hasn't changed since we attempted
25 // to request it. There is the potential for it to transition
// almost immediately to closed or canceled, so we compare
// against open instead of active.
if (spotInstanceRequest.State.Equals("open", StringComparis
on.InvariantCulture))
{
30 anyOpen = true;
break;
}
else if (spotInstanceRequest.State.Equals("active", StringCom
parison.InvariantCulture))
{
35 // Add the instance id to the list we will
// eventually terminate.
instanceIds.Add(spotInstanceRequest.InstanceId);
}
}
40 }
catch (AmazonEC2Exception e)
{
// If we have an exception, ensure we don't break out of
// the loop. This prevents the scenario where there was
45 // blip on the wire.
anyOpen = true;
Console.WriteLine(e.Message);
}
50
if (anyOpen)
{
// Wait for the requests to go active.
Console.WriteLine("Requests still in open state, will retry in 60
seconds.");
55 Thread.Sleep((int)TimeSpan.FromMinutes(1).TotalMilliseconds);
}
} while (anyOpen);
If you just ran the code up to this point, your Spot Instance Request would complete—or possibly fail with
an error. For the purposes of this tutorial, we'll add some code that cleans up the requests after all of
them have transitioned out of the open state.
Step 5: Cleaning up Your Spot Requests and Instances
The final step is to clean up our requests and instances. It is important to both cancel any outstanding
requests and terminate any instances. Just canceling your requests will not terminate your instances,
which means that you will continue to pay for them. If you terminate your instances, your Spot Requests
may be canceled, but there are some scenarios—such as if you use persistent bids—where terminating
your instances is not sufficient to stop your request from being re-fulfilled. Therefore, it is a best practice
to both cancel any active bids and terminate any running instances.
The following code demonstrates how to cancel your requests.
Version v2.0.0
85
AWS SDK for .NET Developer Guide
Tutorial: Amazon EC2 Spot Instances