Kick off second set of code after first set is done in ASP.Net
I have an ASP.Net application that calls an Amazon Web Service to start a virtual machine. Once the user clicks to start the machine, the page posts back to show the list of virtual machines. This part is fine. If the virtual machine has a static IP address assigned to it, a separate API function to Amazon needs to be called once the virtual machine is in a "running state." I don't want the user to have to kick off the 开发者_如何学Goassignment of the static IP, I want it to happen automatically.
My question is should I use a timer and just keep checking if the machine is in running state and then run the second set of code? It seems kind of clunky to me, so I'm not sure if there is any other way (better way) to do this.
I suggest starting a background thread if the VM has a static IP address. You'd call this presumably at the end of the code that starts the VM, before returning the list of VMs.
That background thread could then run in a loop that checks the VM's running state, and then sleeps a few seconds (or more if appropriate) if it isn't yet running. This may seem clunky too, but since you're not able to get a callback when the VM starts running, your code has to check its state every so often. No way to avoid that.
You might also add to the background thread a way to alert someone if the VM doesn't reach a running state after XX minutes.
If you're using C# 4.0, you can take advantage of the Task class:
Task.Factory.StartNew(() => CheckThatVMIsRunningAndAssignStaticIP());
Threading this on the server using a single background thread is not a good idea on ASP.NET. Even disregarding the issues of IIS terminating the background thread (which it can and will do when recycling application pools), you are using up a valuable, limited resource (server threads) when you have a relatively plentiful resource (clients) that can call back periodically to check whether the server has come up yet. Because of that, by using a server thread you'd be seriously constraining your scalability. I'd recommend using a client polling approach with a timer, as you originally planned.
精彩评论