Common stack for some public variables
Someone in stack-overflow answered "stack is attached to a thread, so when the thread exits the stack is reclaimed." But what about public variables how they are managed once thread execution is completed.
For Ex. Declared public variable like
public partial class For开发者_Go百科m1 : Form
{
int k = 10;
private void button1_Click(object sender, EventArgs e)
{
k = k + 5;
}
}
So in this whenever we click button1 a thread is created which updates value of k and then exist so as per this statement stack should be reclaimed and recent value of k should be lost but in reality it store that value and next button click will changes its retain value for ex. from 1) 10 to 15 2)15 to 20 3) 20 to 25 etc....
So My question is where such global variables are stored. Whether any other stack used for global variables. Also I will use object of a class inside a function for ex. such as
public function add (int a, int b)
{
int c;
clsitem objitem = new clsitem();
c=a+b + objitem.id;
retun c;
}
so what will happened of objitem , whether it will store in stack and reclaimed when thread exits or it will stay in heap as it is an object
In your example here, k is not a stack-based variable - it's a field of the Form1 class and is hence stored with the instance of the form.
The two arguments to button1_click are examples of stack-based variables.
Please take a look at this article which explains memory management and garbage collection of C#.NET
http://csharpcomputing.com/Tutorials/Lesson6.htm
精彩评论