【问题标题】:Run a method after finish another one in C#?在 C# 中完成另一个方法后运行一个方法?
【发布时间】:2014-05-29 22:13:55
【问题描述】:

我猜,我在 C#/WPF 中的线程有问题。

如何在一个方法之后运行一个方法来防止像 Null Value 这样的问题。

我认为在下面的代码中,“IF 语句”在“selectLessonContent(selectedLessonId)”方法之前运行,并导致下面的空值问题。

当我在 selectLessonContent(selectedLessonId) 方法之后使用 MessageBox.Show() 时,这个问题就消失了。

    private void btnSelectLesson_Click(object sender, ExecutedRoutedEventArgs e)
    {

            selectLessonContent(selectedLessonId);


        if (selectedUserID != "QuickStart")
        {
            int lessonScore = Int32.Parse(userlessonManager1.selectUserLesson("existCheck", selectedUserID, selectedLessonId).Rows[0][3].ToString());
            if (lessonScore < sectionListview.Items.Count )
            {

                for (int a = 1; a < sectionListview.Items.Count; a++)
                {

                    ListViewItem item = sectionListview.ItemContainerGenerator.ContainerFromIndex(a) as ListViewItem;

                    ContentPresenter templateParent = GetFrameworkElementByName<ContentPresenter>(item);


                    DataTemplate dataTemplate = sectionListview.ItemTemplate;

                    //error occured Here : Value cannot be null.
                    Button btnTemp = dataTemplate.FindName("btnSectionList", templateParent) as Button;

                    btnTemp.IsEnabled = false;
                }
            }
        }

    }

【问题讨论】:

  • 为什么要调用 BeginInvoke?有必要吗?如果是这样,为什么不简单地将其替换为同步 Invoke?
  • BeginInvoke 是异步的,因此它会立即返回。 Dispatcher.BeginInvoke 返回 DispatcherOperation 保存执行操作的状态。还有 DispatcherOperation.Wait()。还有同步 Invoke() 。 (不过,我对调度员还不够熟悉,无法将其作为答案发布)

标签: c# wpf


【解决方案1】:

最简单的解决方案是将所有异步代码包装到一个方法中,这样它将在另一个线程中同步运行。但是一定要小心accessing GUI from another thread

如果您需要更复杂的解决方案,您可以使用 async/await,这可能是 WF/WPF 的最佳选择。

How to wait until await / async methods finish

【讨论】:

    猜你喜欢
    • 2016-03-15
    • 1970-01-01
    • 2011-10-11
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2014-03-21
    • 1970-01-01
    相关资源
    最近更新 更多