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);
- 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.Neil– Neil2019-11-14 10:34:08 +00:00Commented 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.Skizz– Skizz2019-11-14 10:36:58 +00:00Commented Nov 14, 2019 at 10:36
- @Neil Thank you for your insight and I will follow your advice.tomByTheSea– tomByTheSea2019-11-14 10:49:07 +00:00Commented Nov 14, 2019 at 10:49
- @Skizz Thank you, it is a good idea.tomByTheSea– tomByTheSea2019-11-14 10:50:50 +00:00Commented Nov 14, 2019 at 10:50
2 Answers
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.
1 Comment
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()