Is there any way to exit from function only after some object is loaded?
I've created some UserControl. Here is its constructor:
public ZoomableChart()
{
InitializeComponent();
this.mainChart = new MainChart();
this.mainChart.Loaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
{
this.zoomChart = new ZoomChart();
});
}
I don't wa开发者_如何学Cnt to exit from it until mainChart.Loaded event handler execute. Is there any way to do it?
You can create AutoResetEvent
and wait for it.
public ZoomableChart()
{
InitializeComponent();
AutoResetEvent waitLoaded = new AutoResetEvent (false);
this.mainChart = new MainChart();
this.mainChart.Loaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
{
this.zoomChart = new ZoomChart();
waitLoaded.Set ();
});
waitLoaded.WaitOne ();
}
Yes, you can.
public ZoomableChart()
{
InitializeComponent();
AutoResetEvent loaded = new AutoResetEvent(false);
this.mainChart = new MainChart();
this.mainChart.Loaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
{
this.zoomChart = new ZoomChart();
loaded.Set();
});
//better to use timeout here
loaded.WaitOne();
}
Edit: Thanks to Tim. This code will deadlock if this thread was supposed to execute the load. Make sure that this don't happen in same thread.
AutoResetEvent are = new AutoResetEvent(false);
public XoomableChar()
{
InitializeComponent();
this.mainChar = new MainChart();
this.mainChart.Loaded += new RoutedEventHandler(delegate sender, RoutedEventArgs e)
{
this.zoomChart = new ZoomChart();
are.Set();
}
are.WaitOne();
}
精彩评论