【发布时间】: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() 。 (不过,我对调度员还不够熟悉,无法将其作为答案发布)