C# ForEach循环返回三组结果,寻求仅返回最终结果的解决方案
Hey there! I see the issue right away—your current code is adding a new SiteStatus entry to your list every time it finishes checking one URL (inside the finally block of each loop iteration). That's why you're getting three sets of results instead of just the final, fully populated one. Let's fix that step by step.
What's Going Wrong
In your foreach loop, after checking each URL, you're creating a SiteStatus object with the current partial statuses and adding it to statusList. By the end of three loops, you have three entries, each showing the progress of checking sites one by one.
Modified Code
Here's the adjusted version that only returns the final complete status set:
public static List<Models.SiteStatus> GetStatus() { statusList.Clear(); // Website urls to check string site1 = "https://www.google.com"; string site2 = "https://www.google.com"; string site3 = "https://www.google.com"; int site1Status = 0; int site2Status = 0; int site3Status = 0; // Pair each URL with its corresponding status variable for cleaner iteration List<(Uri Url, ref int Status)> urlStatusPairs = new List<(Uri, ref int)> { (new Uri(site1), ref site1Status), (new Uri(site2), ref site2Status), (new Uri(site3), ref site3Status) }; foreach (var pair in urlStatusPairs) { HttpWebResponse response = null; try { HttpWebRequest request = WebRequest.Create(pair.Url) as HttpWebRequest; request.Method = "HEAD"; // Set timeout BEFORE calling GetResponse() (your original code had this after, which didn't work) request.Timeout = 15000; response = request.GetResponse() as HttpWebResponse; // Update the corresponding status for this site pair.Status = (int)response.StatusCode; } catch (Exception) { // Instead of throwing and breaking all checks, leave status as 0 (or set a custom error code) pair.Status = 0; } finally { // Safely close the response if it exists response?.Close(); } } // Create a single SiteStatus entry AFTER all sites are checked var finalStatus = new SiteStatus { url1Site = site1, url1Status = site1Status, url2Site = site2, url2Status = site2Status, url3Site = site3, url3Status = site3Status }; statusList.Add(finalStatus); return statusList; }
Key Changes Explained
- Moved
SiteStatuscreation outside the loop: We now only create oneSiteStatusobject after all URLs have been checked, so your list will only have one entry with all complete statuses. - Fixed timeout placement: The
request.Timeoutis now set beforeGetResponse()—in your original code, it was set after, so the timeout never actually took effect. - Simplified status assignment: Used a tuple list to pair each URL with its corresponding status variable, eliminating those repetitive
ifchecks for matching URIs. - Graceful error handling: Instead of throwing exceptions and stopping the whole process, we just set the failed site's status to 0 (you can adjust this to a custom error code if you prefer).
What You'll Get Now
Your frontend will receive just one result set:
Site 1 = 200 Site 2 = 200 Site 3 = 200
内容的提问来源于stack exchange,提问作者WHoward

