473,714 Members | 2,358 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using Dictionary results in StackOverflowEr ror

After repeatedly calling/using a Dictionary I get a
StackOverflowEr ror. What am I doing wrong?
The situation is as follows:

I have ruler class, this class contains some member variables,
encapsulated properties. SOme of those are calculated when get is
called. These kind of properties are actually Cell classes which have
a Calculation class attached. All Cell properties are stored in a
Dictionary <nameEnum, Cell>

When a Cell property is called, the correct Cell is extracted from the
dictionary and asked for its value. This value is calculated once,
every future call returns the previous calculated value.

Cell Property encapsulation:
public decimal PropertyOne
{
get { return this._myCells[Calc.MyName].Calculate(this ,
this.helper); }
}

If I use the following code, I do _NOT_ get a stackoverflow error. I
can guess/understand what's going on here, but I'd really like to use
the dictionary:

Cell myCell = new Cell(new Calculator());

public decimal PropertyOne
{
get {return this.myCell.Cal culate(this,thi s.helper);
}

It seems as if each cell is recreated upon retrieval from the
dictionary..... ..

Who can help me out?

Apr 10 '07 #1
8 2911
On Apr 10, 11:43 am, "Papa.Coen" <papa.c...@gmai l.comwrote:
After repeatedly calling/using a Dictionary I get a
StackOverflowEr ror. What am I doing wrong?
The situation is as follows:
<snip>

Well, you haven't shown the Calculate method, which could well be
relevant.

Could you post a short but complete program that demonstrates the
problem?
See http://pobox.com/~skeet/csharp/complete.html for what I mean by
that.

Jon

Apr 10 '07 #2
The following code does the trick. You might have to increase the
amount of rulers created.

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Runtime. CompilerService s;

namespace Problem_Dict
{
internal enum Calc
{
PropertyOne
}

public class Program
{
static void Main(string[] args)
{
Program p = new Program();
}

public Program()
{
Ruler firstRuler = this.BuildRuler s();

decimal myVal = firstRuler.Prop ertyOne;
}

private Ruler BuildRulers()
{
Ruler tmpRuler = null;
Ruler previous = null;

Ruler first = null;

for (int i = 1; i <= 5000; i++)
{
tmpRuler = new Ruler();
tmpRuler.Previo us = previous;

if (previous == null)
{
first = tmpRuler;
}

if (previous != null)
{
previous.Next = tmpRuler;
}

previous = tmpRuler;
}

return first;
}
}

public class CalcDemo // : ICalculator
{

public decimal Calculate(Ruler ruler)
{
decimal myVal = 0.0M;

if (ruler.Next != null)
{
myVal += ruler.Next.Prop ertyOne;
}
else
{
myVal = 1;
}

return myVal;
}
}

public class Cell
{
private CalcDemo _iCalc = null;
private decimal _value = 0.0M;
private bool _isCalculated = false;

public Cell(CalcDemo iCalc)
{
this._iCalc = iCalc;
}

[MethodImpl(Meth odImplOptions.S ynchronized)]
public decimal Calculate(Ruler ruler)
{
if(!_isCalculat ed){
this._value = this._iCalc.Cal culate(ruler);
this._isCalcula ted = true;
}

return _value;
}
}
public class Ruler
{
private Ruler _next = null;
private Ruler _previous = null;
private Dictionary<Calc , Cell_cells = null;
public Ruler()
{
this.Build();
}

private void Build()
{
this._cells = new Dictionary<Calc , Cell>();
this._cells.Add (Calc.PropertyO ne, new Cell(new CalcDemo()));
}

public Ruler Next
{
get { return this._next; }
set { this._next = value; }
}

public Ruler Previous
{
get { return this._previous; }
set { this._previous = value; }
}

public decimal PropertyOne
{
get { return this._cells[Calc.PropertyOn e].Calculate(this ); }
}
}
}

Apr 10 '07 #3
On Apr 10, 12:31 pm, "Papa.Coen" <papa.c...@gmai l.comwrote:
The following code does the trick. You might have to increase the
amount of rulers created.
Okay, so the problem is that you've effectively got a linked list, and
when you ask the first element in the list to calculate its value,
that needs to ask the next element, which needs to ask the next, etc.

You may well run out of stack space earlier when using the dictionary
than without using it, but the problem is basically there either way -
you're recursing to a very deep level. Ideally, you want to avoid that
recursion (assuming this kind of depth is normal). The exact nature of
how you do that will depend on the real program (I'm assuming this is
just a cut down version) but you'll effectively need to simulate the
recursion with iteration instead.

Jon

Apr 10 '07 #4
On 10 apr, 14:16, "Jon Skeet [C# MVP]" <s...@pobox.com wrote:
On Apr 10, 12:31 pm, "Papa.Coen" <papa.c...@gmai l.comwrote:
The following code does the trick. You might have to increase the
amount of rulers created.

Okay, so the problem is that you've effectively got a linked list, and
when you ask the first element in the list to calculate its value,
that needs to ask the next element, which needs to ask the next, etc.

You may well run out of stack space earlier when using the dictionary
than without using it, but the problem is basically there either way -
you're recursing to a very deep level. Ideally, you want to avoid that
recursion (assuming this kind of depth is normal). The exact nature of
how you do that will depend on the real program (I'm assuming this is
just a cut down version) but you'll effectively need to simulate the
recursion with iteration instead.

Jon
I do not recurse that deep, I get the error after approx. 344
subsequent calls. My calculation class has a bit (no, it's not a huge
class) more logic than the demo one and I have more calculations than
one. As far as I can see, replacing recursion with iteration poses a
bit of a problem: not every calculation refers to a Next, some refer
to a Previous or to no other cell. there's not a red line that can be
followed on which to base the iteration.

I specifically use the chain of command (like) pattern to simplify a
complex calculation. The mixed 'setup' of the Ruler class the result
of me thinking the calculations could be performed in a linear matter.

Apr 10 '07 #5
Additional info:

The calculations are performed more than once to find the value that
will result to a value of 0 (nil) of a certain property from a certain
ruler instance (the Control ruler). Which ruler is the control ruler
is derived from input parameters. It can be compared by searching a
tree starting somewhere in the middle.

Apr 10 '07 #6
On Apr 10, 1:36 pm, "Papa.Coen" <papa.c...@gmai l.comwrote:

<snip>
I do not recurse that deep, I get the error after approx. 344
subsequent calls.
Well, a stack of 344 calls (*3, at a guess - one for PropertyOne, one
for CalcDemo.Calcul ate and one for Cell.Calculate) is still pretty
huge.
My calculation class has a bit (no, it's not a huge
class) more logic than the demo one and I have more calculations than
one.
It only needs to be a bit bigger to significantly decrease the size
available. Just changing CalcDemo.Calcul ate to have one more decimal
in took the permissable iterations down on my box from about 5570 to
4750. Add a few more things in (which may not be terribly apparent
from your code, even - e.g. a call to a method with lots of
parameters) and you could easily have a large stack frame.
As far as I can see, replacing recursion with iteration poses a
bit of a problem: not every calculation refers to a Next, some refer
to a Previous or to no other cell. there's not a red line that can be
followed on which to base the iteration.
It's often a problem to replace something which is clean in design but
a pain in reality with one which works in reality. You may need to
just simulate recursion in this case by keeping track of results
you're still depending on, and what depends on them, growing a list
appropriately.

Jon

Apr 10 '07 #7
Well, I solved the problem by performing the 'forward' calculations
from end to start. A check is added if the (next) value is already
calculated or not. The rest of the calculations is left untouched but
can be adjusted accordingly if need be.

I really hate this solution because my previous one was good design,
regardless of any con-recursion arguments. Not being able to perform
all (cell based) calculations in a single uniform way prevents me from
implementing a truly (or at least more) generic solution.

As for my comparission to a tree, the app is more like Excel. How
would/does excel perform it's calculations if it's not capable of
recursing through each cell to calculate the value of a cell depending
on more than one other (and interdependant) cell(s)?
Apr 11 '07 #8
On Apr 11, 2:01 pm, "Papa.Coen" <papa.c...@gmai l.comwrote:
Well, I solved the problem by performing the 'forward' calculations
from end to start. A check is added if the (next) value is already
calculated or not. The rest of the calculations is left untouched but
can be adjusted accordingly if need be.
Right.
I really hate this solution because my previous one was good design,
regardless of any con-recursion arguments. Not being able to perform
all (cell based) calculations in a single uniform way prevents me from
implementing a truly (or at least more) generic solution.

As for my comparission to a tree, the app is more like Excel. How
would/does excel perform it's calculations if it's not capable of
recursing through each cell to calculate the value of a cell depending
on more than one other (and interdependant) cell(s)?
I very much doubt that Excel will genuinely recurse arbitrarily - I
expect it simulates it using iteration, just as you've effectively had
to do.

It's the only way which doesn't have this potential problem. Recursing
an arbitrary number of times is always going to go "bang" at some
point, unless tail recursion is implemented/used appropriately (and
the .NET JIT doesn't do tail recursion AFAIK).

Jon

Apr 11 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
30829
by: Asad Khan | last post by:
I have the following method inside I class, public boolean equals(Object o) { return (this.equals(o)); } but when i call this method by "foo.equals(bum)" where foo and bum are some objects, I get a java.lang.StackOverflowError?? I kinda know why its happening; I think it calls the same equals method and
1
1851
by: tarun | last post by:
Hi , I have a heavy GUI apps that works fine on jdk 1.3 . But when running it uding jdk 1.4 , it gives stackOverFlowError. why is that so ???? Thanks Tarun
1
1674
by: t0M | last post by:
It's nearly impossible to find anything on this because of the Dictionary class, included within the dotnet framework, that pollutes any search results pertinent to my question. I want to be able to access an array of words, just like it were a physical dictionary. It's for a stupid little project, but it involves decryption. Is there a file that Word has which contains this collection of words that I can import somehow into my dotnet...
8
7923
by: spohle | last post by:
hi i have a normal dictionary with key and value pairs. now i wanna sort by the keys BUT in a specific order i determine in a list !? any ideas dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} list =
1
2741
by: Nick | last post by:
I am working on a website for a client and one of their requirements was to have a mailing list. I decided to XSLT to transform "templates" to HTML so that editing was very easy and less time consuming. I keep getting the following error when I submit my email to their site. System.Xml.Xsl.XslTransformException: Cannot find the script or external object that implements prefix 'ext:MailingList'. at...
8
3108
by: akameswaran | last post by:
I wrote up a quick little set of tests, I was acutally comparing ways of doing "case" behavior just to get some performance information. Now two of my test cases had almost identical results which was not at all what I expected. Ultimately I realized I don't really know how literals are treated within the interpreter. The two implementations I was looking at were: class caseFunction(object): def __init__(self):
5
1947
by: Bill Jackson | last post by:
What is the benefit of clearing a dictionary, when you can just reassign it as empty? Similarly, suppose I generate a new dictionary b, and need to have it accessible from a. What is the best method, under which circumstances? .... a = b
0
2045
by: napolpie | last post by:
DISCUSSION IN USER nappie writes: Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file. This file is long file and it's composed by word and number arguments like this: GRILLE EURAT5 Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-E Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file.
6
1703
by: asincero | last post by:
Which is better: using an if/else construct to simulate a C switch or use a dictionary? Example: def foo(): if c == 1: doCase1() elif c == 2: doCase2() elif c == 3: doCase3()
0
8808
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8712
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9077
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4465
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4727
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3159
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.