c# - 递归调用线程方法(System.Threading)是不好的做法吗?

标签 c# multithreading recursion

请原谅我的术语,我对 System.Threading 不太熟悉,但如果我有如下内容:

private static int _index;
private static List<int> _movieIds = new List<int>();

static void Main(string[] args)
{
    // the below call populates the _movieIds list variable with around 130,000 ints
    GetListOfMovieIdsFromDatabase(); 

    _index = 0;
    Thread myThread = new Thread(DoWork);
    myThread.Start();
}

public static void DoWork()
{
     // do something with the value of _index (iterate through the _movieIds list) then recursively call DoWork() again

     Thread.Sleep(400);

     _index++;

     DoWork();
}

这是不好的做法吗?我正在遍历 int's 的私有(private)静态列表在类级别定义为成员,因此 DoWork() 的第一次迭代将使用 _index 的第一个值(为了简单起见,我没有解释),那么第二次迭代(递归调用)将使用第二个值 _index , 等等。

我问这个的原因是因为在运行这个应用程序大约 12 小时后我得到了一个堆栈溢出异常,我相信这是因为递归调用。

最佳答案

是的。您最终总会出现堆栈溢出,因为调用堆栈永远没有机会展开。

而不是增加你的index通过递归调用变量,在你的线程中使用循环。

public static void DoWork()
{
     while(true)
     {    
          // do something with the value of _index (iterate through the _movieIds list) then recursively call DoWork() again

         Thread.Sleep(400);

         _index++;

         // break when a condition is met   
      }
}

关于c# - 递归调用线程方法(System.Threading)是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340182/

相关文章:

C#,有效 ModelState 失败 .isValid

c# - 将项目从紧凑型框架 .NET 转换为完整框架 .Net

c# - .NET 的最佳 NoSQL DB 来存储大量带有时间索引的分钟统计数据?

c# - 线程重命名

ios - 异步 swift 3

java - 如果给我一堆组合,每个组合都有 k-1 个元素,如何生成大小为 k 个元素的列表?

c# - 多态模型可绑定(bind)表达式树解析器

multithreading - 锁定多个读者单个作家

java - 将值从内部递归方法传递到外部方法

c - 递归函数有一些限制吗?例如 : how many layers does the function require?