有没有办法在加载某个对象后退出函数?

时间:2010-08-25 11:46:44

标签: c#

我创建了一些UserControl。这是它的构造函数:

public ZoomableChart()
        {
            InitializeComponent();

            this.mainChart = new MainChart();
            this.mainChart.Loaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
                {
                    this.zoomChart = new ZoomChart();
                });
        }

在mainChart.Loaded事件处理程序执行之前,我不想退出它。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以创建AutoResetEvent并等待它。

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

答案 1 :(得分:2)

是的,你可以。

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

修改:感谢蒂姆。如果该线程应该执行加载,则此代码将死锁。确保在同一个线程中不会发生这种情况。

答案 2 :(得分:0)

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