Reputation: 574
I'm currently writing an IRC bot/client and I have stumbled upon a small problem. Every channel is to be displayed in a separate window with its own set of controls. I have created an appropriate window class ChanWindow:
public partial class ChanWindow : Form
{
string Chan;
string Username;
IRCBot Caller;
public ChanWindow(string channame, string uname, IRCBot caller)
{
Caller = caller;
Caller.Join(channame);
InitializeComponent();
Chan = channame;
Name = Chan;
Username = uname;
}
//various functionalities required for window use
}
I'm storing the window objects in a ConcurrentDictionary<string, ChanWindow>
, because there is (supposed to be) a separate thread sending appropriately edited messages to windows. They are all initialized in a loop:
foreach (string chan in Chanlist)
{
Chans[chan] = new ChanWindow(chan, Name, this);
Chans[chan].Show();
}
Where Chanlist
is a List<string>
of channels to join.
Having witnessed the windows die shortly after the program starts, I put a breakpoint in the line Username = uname;
of ChanWindow constructor and noticed it being tripped immediately before the window's death.
My main question is: what is the cause and how can I avoid it? Is using a Dictionary a good idea? Should I build some sort of wrapper/container class which would handle the window's functionality?
Upvotes: 2
Views: 319
Reputation: 35746
I suspect you don't have
Application.Run(new ChanWindow());
in your main entry point (Program.Main()
by default).
If you don't make the main GUI thread Show
the form, and wait for it to close, nothing will stop the thread from completeing and your application closing.
If you want to start the message loop independently you will still need to call Application.Run()
so the main thread will start handling events. If you call it without a parameter the message loop won't stop automatically so you'll have to call Application.Exit()
explicitly when you want the message loop to stop. Then the main thread will then continue to the end of the program and end.
You could just do this to your code,
foreach (string chan in Chanlist)
{
Chans[chan] = new ChanWindow(chan, Name, this);
Chans[chan].Show();
}
Application.Run();
but, if you want to automatically exit the application you could inherit your own ApplicationContext
, as outlined in the already linked MSDN documentation, and pass that to Application.Run()
, that is what its for after all.
Upvotes: 4