[英]Any way to use stackalloc while avoiding stackoverflow exception
In C# .NET, stackalloc
keyword is very fascinating in order to avoid heap allocation.在 C# .NET 中,为了避免堆分配, stackalloc
关键字非常有趣。 However, my concern is that using stackalloc
might cause a stackoverflow
exception.但是,我担心的是使用stackalloc
可能会导致stackoverflow
异常。 For the purpose of avoiding the exception, is there any good way to use stackalloc
while avoiding stackoverflow
exception?为了避免异常,有没有什么好的方法可以在避免stackoverflow
异常的同时使用stackalloc
呢? I originally came up with the following code, but I did not figure out how I should get the remaining stack size.我最初想出了以下代码,但我没有弄清楚我应该如何获得剩余的堆栈大小。
void Main()
{
var remainingStackSize = //Get remaining stacksize somehow.
var arraySize = 100;
if (remainingStackSize > sizeof(byte) * arraySize)
{
Span<byte> numbers = stackalloc byte[arraySize];
}
else
{
Span<byte> numbers = new byte[arraySize];
}
}
From the documentation :从文档中:
The amount of memory available on the stack is limited.堆栈上可用的 memory 数量有限。 If you allocate too much memory on the stack, a StackOverflowException is thrown.如果在堆栈上分配过多的 memory,则会引发 StackOverflowException。 To avoid that, follow the rules below:为避免这种情况,请遵循以下规则:
Limit the amount of memory you allocate with stackalloc.使用 stackalloc 限制您分配的 memory 的数量。 Because the amount of memory available on the stack depends on the environment in which the code is executed, be conservative when you define the actual limit value.因为堆栈上可用的 memory 的数量取决于执行代码的环境,所以在定义实际限制值时要保守。
Avoid using stackalloc inside loops.避免在循环内使用 stackalloc。 Allocate the memory block outside a loop and reuse it inside the loop.在循环外分配 memory 块并在循环内重用它。
See also How much stack usage is too much?另请参阅多少堆栈使用量过多?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.