【问题标题】:How to change stack size of a console application? [duplicate]如何更改控制台应用程序的堆栈大小? [复制]
【发布时间】:2012-08-25 10:54:48
【问题描述】:

可能重复:
How to change stack size for a .NET program?

我想更改以下控制台应用程序的堆栈大小:

using System;
using System.IO;

class Test {

    static int n;
    static bool[] us;
    static int[,] matr;

    static void dfs(int a) {
        us[a] = true;
        for (int b = 0; b < n; b++) {
            if (!us[b]) {
                dfs(b);
            }
        }
    }

    static void Main() {
        StreamReader input = new StreamReader("input.txt");
        StreamWriter output = new StreamWriter("output.txt");
        string[] snum = input.ReadLine().Split(' ');
        n = int.Parse(snum[0]);      // number of vertices
        int m = int.Parse(snum[1]);  // number of edges
        us = new bool[n];
        matr = new int[n, n];
        for (int i = 0; i < m; i++) {
            snum = input.ReadLine().Split(' ');
            int a = int.Parse(snum[0]) - 1, b = int.Parse(snum[1]) - 1;
            matr[a, b] = matr[b, a] = 1;
        }
        for (int i = 0; i < n; i++) {
            if (!us[i]) {
                dfs(i);
            }
        }
        input.Close();
        output.Close();
    }
}

n 近似时。 100,000,dfs 的深度约为。 100,000 并且应用程序抛出 StackOverflowException

我知道默认堆栈大小是 1 MB,但我不知道如何更改它。

【问题讨论】:

  • 考虑在没有方法递归的情况下实现 dfs
  • 为什么 dfs 还是递归的?将所有值设置为某个索引到true,这看起来像是一种过于昂贵的方法。
  • 实际上它只是 DFS - 考虑图形的其他有用算法的基础。我认为只有 DFS 会是更清晰的递归示例。

标签: c# stack-overflow stack-size


【解决方案1】:

指定更大堆栈大小的最简单方法是创建一个新线程——有一个构造函数重载允许您指定大小。将逻辑移至新方法,然后在 Main 方法中创建一个具有更大堆栈大小的新线程来运行新方法。示例:

    static void Main() {
        const int stackSize = 0x400000;
        var thread = new Thread(NewMethod, stackSize);
        thread.Start();
        thread.Join();
    }

    static void NewMethod() { 
        StreamReader input = new StreamReader("input.txt"); 
        StreamWriter output = new StreamWriter("output.txt"); 
        string[] snum = input.ReadLine().Split(' '); 
        n = int.Parse(snum[0]); 
        int m = int.Parse(snum[1]); 
        us = new bool[n]; 
        matr = new int[n, n]; 
        for (int i = 0; i < m; i++) { 
            snum = input.ReadLine().Split(' '); 
            int a = int.Parse(snum[0]) - 1, b = int.Parse(snum[1]) - 1; 
            matr[a, b] = matr[b, a] = 1; 
        } 
        for (int i = 0; i < n; i++) { 
            if (!us[i]) { 
                dfs(i); 
            } 
        } 
        input.Close(); 
        output.Close(); 
    } 

如果您无法更改源代码,也可以使用 EDITBIN。详情见这个答案:https://stackoverflow.com/a/2556970/385844

【讨论】:

    【解决方案2】:
    int stackSize = 1024*1024*64;
    Thread th  = new Thread( ()=>
        {
            //YourCode
        },
        stackSize);
    
    th.Start();
    th.Join();
    

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2017-03-18
      • 2016-07-09
      • 2017-04-19
      • 2019-09-17
      相关资源
      最近更新 更多