【问题标题】:C# Recursive function approach?C#递归函数方法?
【发布时间】:2015-05-15 18:11:36
【问题描述】:

我在 Windows 服务中有一个递归函数。此函数在完成后会自动倒带,因为它已在递归中重复多次。这不是开销吗?

有什么办法可以避免放松吗?有没有更好的办法?

编辑:在这种方法中,我从数据库中获取 100 条记录,然后对其进行处理,然后再获取 100 条,依此类推,直到数据库中的所有记录都已处理完毕。

此外,数据库中的总记录数没有限制,因此此函数可以重复很多次。

public void ServiceFunctionality()
{
    try
    {
        // Get Data From WEBAPI
        HttpClient client = new HttpClient();
        HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
        Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;

        if (objResponse != null)
        {
            if (objResponse.isSuccess == true)
            {
                listContact = objResponse.data.lContact;
                int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
                int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;

                if (listContact != null && listContact.Count>0)
                {
                    try
                    {
                        Parallel.ForEach(listContact, contact =>
                        {
                            // some code...
                        });
                        // Recursive Call
                        if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
                        {
                            ServiceFunctionality();
                        }
                    }
                    catch (Exception ex)
                    {
                        // Logging
                    }
                }
            }
            else
            {
                // Logging
            }
        }
        else
        {
            // Logging
        }
    }
    catch (Exception ex)
    {
        // Logging
    }
} 

【问题讨论】:

  • 如果你可以让它尾递归,编译器可能会提高它的效率。或者您可以尝试将一些异常处理推送到递归之外。
  • “过早的优化是万恶之源”。如果您真的认为这是一个问题,请运行一些测试来计时您的方法的执行。如果您的测试表明这是一个问题,则进行优化。
  • @ryanyuyu - 恐怕不在 C# 中 :( 见 stackoverflow.com/questions/491376/…
  • 你能用while循环代替吗?
  • 顺便说一句,我认为这里没有真正需要递归。一个简单的循环可能会更好,并防止潜在的堆栈溢出。

标签: c# recursion


【解决方案1】:

你总是可以放松到一个while循环。因为您的调用不会改变状态,所以这很简单。

public void ServiceFunctionality()
{
    bool done = false;
    while(!done) {
    try
    {
        done = true; //if we don't reset this, we're done.
        // Get Data From WEBAPI
        HttpClient client = new HttpClient();
        HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
        Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;

        if (objResponse != null)
        {
            if (objResponse.isSuccess == true)
            {
                listContact = objResponse.data.lContact;
                int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
                int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;

                if (listContact != null && listContact.Count>0)
                {
                    try
                    {
                        Parallel.ForEach(listContact, contact =>
                        {
                            // some code...
                        });
                        // set loop variable
                        if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
                        {
                            done = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Logging
                    }
                }
            }
            else
            {
                // Logging
            }
        }
        else
        {
            // Logging
        }
    }
    catch (Exception ex)
    {
        // Logging
    }
} 
}

【讨论】:

    【解决方案2】:

    当您有其他合适的解决方案时,不要使用递归来调用函数。我个人几乎从不这样做

    除了使用一段时间外,我试图保持它不变..

    不要忘记打破循环。我试图处理这件事,但仍然

    只是要非常小心,永远不要冒险在服务器上无限循环我接受了maxPossibleIterations。这样万一出现任何错误,您的 Web 服务服务器就不必进行无限迭代

    public void ServiceFunctionality()
    {
        long maxPossibleIterations = 999999;
        try
        {
            while (true)
            {
            maxPossibleIterations++;
            // Get Data From WEBAPI
            HttpClient client = new HttpClient();
            HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
            Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
    
            if (objResponse != null)
            {
                if (objResponse.isSuccess == true)
                {
                    listContact = objResponse.data.lContact;
                    int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
                    int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
    
                    if (listContact != null && listContact.Count>0)
                    {
                        try
                        {
                            Parallel.ForEach(listContact, contact =>
                            {
                                // some code...
                            });
                            if (MaxPKinTotalRecords == MaxPKinSelectedRecords)
                            {
                                break;
                            }                        
                        }
                        catch (Exception ex)
                        {
                            // Logging
                        }
                    }
                    else
                        break; //Important
                }
                else
                {
                    // Logging
                    break;
                }
            }
            else
            {
                // Logging
                break;
            }
            } // End while
        }
        catch (Exception ex)
        {
            // Logging
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2016-02-13
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多