Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Created May 1, 2012 02:55
Show Gist options
  • Save peteraritchie/2564623 to your computer and use it in GitHub Desktop.
Save peteraritchie/2564623 to your computer and use it in GitHub Desktop.
update
private void updateServerStatus()
{
foreach (ServerItem server in ServerItems)
{
var capturedServer = server;
server.ServerImage = "/Images/appbar.questionmark.rest.png";
string url = server.ServerAddress;
if (url.StartsWith("http://") || url.StartsWith("https://")) { }
else
{
url = "http://" + url;
}
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.BeginGetResponse(result => updateServerStatusImage(result, capturedServer, (HttpWebResponse)req.EndGetResponse(result)), null);
}
catch
{
server.ServerImage = "/Images/appbar.cancel.rest.png";
serverDB.SubmitChanges();
}
}
}
private void updateServerStatusImage(IAsyncResult result, ServerItem server, HttpWebResponse response)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
server.ServerImage = "/Images/circle-green.png";
serverDB.SubmitChanges();
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
server.ServerImage = "/Images/circle-red.png";
serverDB.SubmitChanges();
});
}
}
@peteraritchie
Copy link
Author

I've gotten rid of the endWebRequest method (cleaner to me :).
Also note that I've added a captureServer variable in the loop. What you had before was accessing a modified closure. This mean that your asynchronous code could have accessed a reference to a variable the likely be updated by the next iteration of the loop before the asynchronous code (the lambda) was executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment