1

Create a Thread in C#, the constructor has a parameter maxStackSize, I don't know how big its value should be, how should I estimate the value of maxStackSize? Constructor like this: public Thread (System.Threading.ThreadStart start, int maxStackSize);

4
  • Do not do this. Use modern C# ideas like thread pool and tasks. There are very few reasons to manually create a thread these days. Commented Nov 14, 2019 at 10:34
  • The max stack size parameter is optional, so unless you have a really good reason to limit it, just ignore it and let the system take care of it. Commented Nov 14, 2019 at 10:36
  • @Neil Thank you for your insight and I will follow your advice. Commented Nov 14, 2019 at 10:49
  • @Skizz Thank you, it is a good idea. Commented Nov 14, 2019 at 10:50

2 Answers 2

1

The default value of the stack is 1MB, and there is very little reason to make it bigger. A bigger stack might be needed if you must have a very deep recursion, for example. However, then 4MB (the maximum size possible) might not able to help either and you better look at a different algorithm.

The idea to define the stack is mostly to define size smaller than 1MB. Since the stack must be allocated in physical memory, when the thread is running, if you know your code is small and doesn't have recursion or deep calls, you can specify a smaller stack size.

In general, just go with the default stack size.

EDIT: NET CLR (starting 4.0) doesn't commit the full 1MB in memory. In commits only 100K, expecting these will be enough; however, it does reserve 1MB of virtual address space.

Sign up to request clarification or add additional context in comments.

1 Comment

I am very grateful for your in-depth explanation. Thank you very much.
-1

Here is just an example that creates a thread with stack size of 30 MBs:

var thread = new Thread( start: () => { Span<int> numbers = stackalloc int[7_000_000]; // 4 bytes x 7 million records = 28 megabytes Console.WriteLine("Allocated an array of integers on the stack"); }, maxStackSize: 30_000_000 // 30 megabytes ); thread.Start(); thread.Join(); 

Code above just prints:

Allocated an array of integers on the stack 

However, if you try to allocate an array of 8 millions of records, you get StackOverflowException:

Stack overflow. at Program+<>c.<<Main>$>b__0_0() at System.Threading.Thread.StartCallback() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.