How to change stack size of a console application?

2019-07-09 01:19发布

问题:

Possible Duplicate:
How to change stack size for a .NET program?

I want to change the stack size for the following console application:

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();
    }
}

When n is aprox. 100,000, the depth of dfs is aprox. 100,000 and the application throws a StackOverflowException.

I know that the default stack size is 1 MB, but I do not know how to change it.

回答1:

int stackSize = 1024*1024*64;
Thread th  = new Thread( ()=>
    {
        //YourCode
    },
    stackSize);

th.Start();
th.Join();


回答2:

The easiest way to specify a larger stack size is to create a new thread -- there's a constructor overload that allows you to specify the size. Move the logic to a new method, then, in the Main method, create a new thread with a larger stack size to run the new method. Example:

    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(); 
    } 

You can also use EDITBIN, if you're not able to change the source code. See this answer for details: https://stackoverflow.com/a/2556970/385844