static readonly字段导致StackOverflowException

时间:2017-01-17 10:06:37

标签: c# stack-overflow

在ASP.NET网站中,我有static readonly XGeoPhone provider = new XGeoPhone();。在XGeoPhone课程内,我有static readonly XPhoneInfo[] phoneInfo = new[] { new XPhoneInfo(......), ... 250000 more objects ... }。当我在开发者计算机或真实服务器上运行它时 - 它会在new XGeoPhone()StackOverflowException崩溃。我不太明白它试图在堆栈上创建这个巨大的数组,而不是堆?发生了什么事?

更新:最简单的版本将崩溃:

public partial class XGeoPhone
{
    public XPhoneInfo GetInfo(long phone)
    {
        return
            phoneInfos.
            FirstOrDefault(pi =>
                pi.Start <= phone &&
                phone <= pi.End);
    }

    static readonly XPhoneInfo[] phoneInfos = new[]
    {
        new XPhoneInfo(2000000000, 2099999999, XCountryId.EG, null, null),
        new XPhoneInfo(2120000000, 2129999999, XCountryId.MA, null, null),
        new XPhoneInfo(2130000000, 2139999999, XCountryId.DZ, null, null),
        new XPhoneInfo(2160000000, 2169999999, XCountryId.TN, null, null),
        new XPhoneInfo(2180000000, 2189999999, XCountryId.LY, null, null),
        .........
    }
}

public class XPhoneInfo
{
    public XPhoneInfo(long start, long end, XCountryId? country, string region, string provider)
    {
        this.Start = start;
        this.End = end;
        this.Country = country;
        this.Region = region;
        this.Provider = provider;
    }

    public long Start { get; private set; }
    public long End { get; private set; }
    public XCountryId? Country { get; private set; }
    public string Region { get; private set; }
    public string Provider { get; private set; }
}

class Program
{
    static readonly XGeoPhone g = new XGeoPhone();

    static void Main(string[] args)
    {
        var v = g.GetInfo(79054567890);
    }
}

1 个答案:

答案 0 :(得分:-1)

好的,我找到了解决方法 - 我可以创建一个线程并在线程的构造函数中指定堆栈大小,如所描述的here。有用。但我决定将那个大数组移动到csv文件。