How can I do that?
Under destroying I mean remove it from the memory.
An example (Form1 is some form):
static void Main()
{
Test();
// here we still have A alive
// GC.Collect() doesn't helps
Form1 B = new Form1();
Application.Run(B);
// problem is here: B and A "collides", due to assumption what A is already dead
}
public static Test()
{
Form1 A = new Form1();
// do something with A, but not displaying form
// I was sure what A will disappears after Test()
}
Could the problem be certain components used on form? Timers, which are created in constructor? Or is it a normal way for A to exists that long?
Update
Collides - means they are using something what is exclusive to a single user only. How can I push the process of removing A from memory?
Please, do not be rushy (thanks for -2), I am at work, so can't update fast. I am trying to be as clear as I can.
Whenever you can, please avoid using cliches GC.Collect is always bad, etc. I know that. As you can see all I need a sort of manipulations with the form before software runs, so no performance or any other sort of issue is expected. It may be not the best case, but please then, tell me the better one. Doing something with A is a necessary test, yes.
The problem is: after doing test with A, I want it to disappear. Of course I can modify A in a way what it will not have timers, components, etc. But there are dozens of forms already. And all has to be tested. And I simply didn't knew that what A will exists after Test().
Update 2
I really want to know why question has -3. What I learned today is when you create a form, it will exists until the end of application and there is now known way to kill it. Timers, created in constructor will keep running, components will try to access something they shouldn't, etc. Whole lots of things will changes as soon as you care to create second instance of working (as it seems) form.
Update 3
Lets make a simple test:
static class Program
{
public static bool Test { get; set; }
static void Main()
{
DoTest();
Test = true;
Application.Run(new Form1());
}
static void DoTest()
{
var A = new Form1();
var B = new Form1();
var C = new Form1();
//A.Dispose();
//B.Dispose();
//C.Dispose();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Program.Test)
{
timer1.Stop();
MessageBox.Show("123");
}
}
}
It will show 4 message boxes (from main window and from undead A, B, C). Before today I was 100% sure, what whatever I put on form will be deleted together with form. And whenever I create a local variable - it is going to be local. But it seems it is not. And this is a problem - un-obvious behavior.
It looks like Thorsten Dittmar solution with Dispose()
should do a trick. I should look myself into my components (shutting their timers manually, etc).