开发者

Is there any way to exit from function only after some object is loaded?

开发者 https://www.devze.com 2023-01-13 15:31 出处:网络
I\'ve created some UserControl. Here is its constructor: public ZoomableChart() { InitializeComponent();

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号