Created
May 1, 2012 02:55
-
-
Save peteraritchie/2564623 to your computer and use it in GitHub Desktop.
update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.