I have my two classes MainWindow
and Foo
and have a slight problem considering timing:
class MainWindow : Window
{
internal void SomeMethod(string name)
{
Foo foo = new foo(name)
foo.MyEventHandler += EventHandlerMethod;
}
internal void EventHandlerMethod(object sender, EventArgs e)
{
//do something after foo is done initializing stuff
}
}
class Foo
{
internal event EventHandler MyEventHandler;
internal Foo(string name)
{
//start another thread that will at some point via event call FooMethod()
}
private void FooMethod()
{
MyEventHandler(this, null);
}
}
The problem is that I cannot guarantee how long the Foo
-initialized thread will take and FooMethod();
might be called before MyEventHandler
has been added.
I thought of a possible solution to simply not add the initializer but have a separate method and simply call that one after adding the event, but in general, is there a way to add events BEFORE the initializer is called?
you can't do before, but you can doing it as part of the constructor. Just pass the handler in as a parameter.
However, that's pretty ugly. Having constructors that spawn threads is not nice, much better having a "Start" method