I believed that manually calling System.GC.Collect() only effect performance or memory usage of application. But in this example, calling System.GC.Collect() changes application's action.
using System;
using System.Windows.Forms;
public class Form1 : Form
{
public Form1()
{
this.Click += Form1_Click;
}
private void Form1_Click(object sender, EventArgs e)
{
CreateMyEventHandler()(sender, e);
//System.GC.Collect();
}
private EventHandler CreateMyEventHandler()
{
return (sender, e) =>
{
var cm = new ContextMenu(new[]
{
new MenuItem("Menu item", (sender2, e2) =>
{
Console.WriteLine("Menu item is clicked!");
})
});
cm.Show(this, ((MouseEventArgs)e).Location);
};
}
}
static class Program
{
static void Main()
{
Application.Run(new Form1());
}
}
Save above code into a file "Program.cs" and run it as following.
csc Program.cs
.\Program.exe
It opens window as figure below.
Clicking the window opens context menu, and clicking the menu item prints text massage "Menu item is clicked!" to the console, as expected.
However, with uncommenting the line commented out in above example:
System.GC.Collect();
The action of application changes. Clicking menu item prints nothing.
This was unexpected for me. So why it changes? And how do I prevent unexpected change of this kind in real application?
This example is confirmed with Visual Studio 2013.
Aucun commentaire:
Enregistrer un commentaire