我正在一个单独的线程中加载一个大树视图。此线程从窗体的加载事件开始。如何检查表单仍然'活着'
一切顺利,直到加载事件发生错误。发生错误时,我关闭表单,加载我的树视图的线程必须中止。但我不知道该怎么做。
问题是,窗体关闭,线程仍在工作,所以我得到一个InvalidOperationException
。该计划分解和线程的这部分强调:
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
tvQuestionnaire.Nodes.Add(catNode);
});
我的形式树形视图被称为tvQuestionnaire
。整个功能(在我的后台工作者中调用)如下所示:
private void SetTreeviewData()
{
// Get all categories
List<Category> categories = _questionnaire.GetCategoriesFromQuestionnaire();
// Get all questions which are retrieved by the question manager
OrderedDictionary all_ordered_questions = _questionManager.AllQuestions;
// Store all the questions in a List<T>
List<Question> all_questions = new List<Question>();
foreach (DictionaryEntry de in all_ordered_questions)
{
Question q = de.Value as Question;
all_questions.Add(q);
}
foreach (Category category in categories)
{
// Create category node
TreeNode catNode = new TreeNode();
catNode.Text = category.Description;
catNode.Tag = category;
catNode.Name = category.Id.ToString();
// Get all questions which belongs to the category
List<Question> questions = all_questions.FindAll(q => q.CategoryId == category.Id);
// Default set the font to bold (Windows issue)
Font font = new Font(tvQuestionnaire.Font, FontStyle.Regular);
foreach (Question question in questions)
{
// Create question node
TreeNode queNode = new TreeNode();
queNode.Text = question.Question;
queNode.Tag = question;
queNode.Name = "Q" + question.Id;
queNode.NodeFont = font;
// Determine which treenode icon to show
SetTreeNodeIcon(ref queNode, question);
// Add node to category node
catNode.Nodes.Add(queNode);
}
if (_closing)
return;
// Add category node to treeview
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
tvQuestionnaire.Nodes.Add(catNode);
// Now the category (and thus the questions) are added to treeview
// Set questions treenode icon
//SetTreeNodeIcon(questions);
});
}
// Set each category under its parent
for (int i = tvQuestionnaire.Nodes.Count - 1; i >= 0; i--)
{
Category category = tvQuestionnaire.Nodes[i].Tag as Category;
TreeNode node = tvQuestionnaire.Nodes[i];
if (IsWindow(this.Handle.ToInt32()) == 0)
return;
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
if (category.ParentId == null)
return;
else
{
// Find parent node
TreeNode[] parentNodes = tvQuestionnaire.Nodes.Find(category.ParentId.ToString(), true);
//Remove current node from treeview
tvQuestionnaire.Nodes.Remove(node);
parentNodes[0].Nodes.Insert(0, node);
}
});
}
}
这是我的后台工作人员调用的唯一方法。
所以我的问题是,我怎样才能防止发生异常?如何检查树形视图所在的表单,仍然“活着”?