0

I guess, I have problem with threading in C#/WPF .

How to run a method right after another one for prevent some problem like Null Value .

I think in this below code "IF statment" run before "selectLessonContent(selectedLessonId)" method and cause a Null Value problem in below.

when I use MessageBox.Show() right after selectLessonContent(selectedLessonId) method this problem gone.

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

    }
  • 1
    Why do you call BeginInvoke? Is it at all necessary? If so, why not simply replace it with a synchronous Invoke? – Clemens May 29 '14 at 06:12
  • BeginInvoke is asynchronous, so it returns immediately. Dispatcher.BeginInvoke returns DispatcherOperation that holds status of the executing action. There is also DispatcherOperation.Wait(). And there is synchronous Invoke() too. (I'm not familiar with dispatcher enough to post it as an answer though) – Arie May 29 '14 at 06:26

1 Answers1

0

Simplest solution is wrap all asynchronous code to one method, so it will run synchronously in another thread. But you must careful accessing GUI from another thread

If you need more sophisticated solution, you can use async/await which is probably the best for WF/WPF.

How to wait until await / async methods finish

Community
  • 1
  • 1
Jan Remunda
  • 7,840
  • 8
  • 51
  • 60