You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# ForEach循环返回三组结果,寻求仅返回最终结果的解决方案

Fix: Return Only the Final Complete Status Set in Your C# Code

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

  1. Moved SiteStatus creation outside the loop: We now only create one SiteStatus object after all URLs have been checked, so your list will only have one entry with all complete statuses.
  2. Fixed timeout placement: The request.Timeout is now set before GetResponse()—in your original code, it was set after, so the timeout never actually took effect.
  3. Simplified status assignment: Used a tuple list to pair each URL with its corresponding status variable, eliminating those repetitive if checks for matching URIs.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:43:10