WPF - 在下次运行之前等待任务完成

时间:2017-02-11 17:33:46

标签: c# wpf visual-studio-2015 task .net-4.5

我希望在直接继续下一个操作之前等待操作完成。

(操作1)程序反序列化视图模型并在数据网格中显示数据。

(Operation2)程序设置窗口所需的高度。

(Operation3)程序渲染并保存数据网格的图像。

(Operation4)程序关闭。

目前程序崩溃是因为我认为某些操作没有正确完成所需的时间。当我在代码顶部有一个消息框显示时,它运行正常。在VS 2015 .net 4.5中工作,我该如何实现这一目标?

        //MessageBox.Show("Hello");
        BinaryFormatter reader = new BinaryFormatter();
        using (var file = File.Open(v, FileMode.Open))
        {
            this.Vm = (ViewModel)reader.Deserialize(file);
        }
        this.DataContext = Vm;


        myRef = (CollectionViewSource)this.Resources["ColViewSource"];

        properHeight = (myRef.View.Groups.Count - 1) * 50;

        foreach (var item in Vm.Collection)
        {

            properHeight += 55;
        }
        this.Height = properHeight;
        CreateBitmapFromVisual(grid, "picture.png");
        Application.Current.Shutdown();

2 个答案:

答案 0 :(得分:0)

我不认为您的应用因为发布的示例代码而崩溃了。当您尝试使用以下行关闭应用程序时,项目中必须有一些其他代码导致崩溃。

  Application.Current.Shutdown();

更不用说你可以在调试模式下使用F10验证代码。

答案 1 :(得分:0)

使用以下内容确保一切准备就绪:

 Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.ContextIdle, null);

This table可能会帮助您确定哪个 DispatcherPriority 更合适。