我如何知道我的线程是否已经完成了任务?(C#winforms)
使用下面的代码,我如何知道我的线程是否已经完成了任务?我的目的是杀死线程以释放内存。或者我该怎么做我如何知道我的线程是否已经完成了任务?(C#winforms),c#,winforms,multithreading,C#,Winforms,Multithreading,使用下面的代码,我如何知道我的线程是否已经完成了任务?我的目的是杀死线程以释放内存。或者我该怎么做 private delegate void DelegateSetProperties(DataTable dataSource, string valueMember, string displayMember); Thread thread1; DelegateSetProperties delegateSetProperties; private void For
private delegate void DelegateSetProperties(DataTable dataSource, string valueMember, string displayMember);
Thread thread1;
DelegateSetProperties delegateSetProperties;
private void Form1_Load(object sender, EventArgs e)
{
delegateSetProperties = new DelegateSetProperties(SetProperties);
thread1 = new Thread(new ThreadStart(InitValues));
thread1.IsBackground = true;
thread1.Start();
// should I abort thread1 here? if I abort it, does it frees the memory occupied by thread1?
}
private void SetProperties(DataTable dataSource, string valueMember, string displayMember)
{
comboBox1.DataSource = dataSource;
comboBox1.ValueMember = valueMember;
comboBox1.DisplayMember = displayMember;
comboBox1.SelectedIndex = 0;
}
void InitValues()
{
var dt = new DataTable
{
TableName = "CATEGORY",
Columns = {
{"CategoryCode", typeof(string)},
{"Name", typeof(string)},
}
};
dt.Rows.Add("C1", "Category1");
dt.Rows.Add("C2", "Category2");
dt.Rows.Add("C3", "Category3");
// and so on...
comboBox1.Invoke(delegateSetProperties, new object[] { dt, "CategoryCode", "Name"
});
}
除非进程已经病入膏肓,而且无论如何都会死掉,否则不要中止线程。发生了非常糟糕的事情(例如,无法恢复的锁)。代码很好。当
InitValues
方法结束时,线程也将结束
如果
您可能想考虑添加一些异常处理,以便如果<代码> IITValue抛出它不会杀死整个<代码> AppDeals,并且您应该理解,这里大部分时间都将用于更新UI线程上的UI。(除非您的表是从外部源填充的,并且过程中的
行。Add
只是说明性的)。除非您的进程已经病入膏肓,而且无论如何都会死掉,否则不要中止线程。非常糟糕的事情会发生(例如,无法恢复的锁)。代码仍然很好。当InitValues
方法结束时,线程也会结束
如果
您可能想考虑添加一些异常处理,以便如果<代码> IITValue抛出它不会杀死整个<代码> AppDeals,并且您应该理解,这里大部分时间都将用于更新UI线程上的UI。(除非您的表是从外部源填充的,并且过程中的
行.Add
只是说明性的)。一个选项是Thread.Join。这将使主线程等待子线程完成执行,然后再继续
另一个选项是查看System.ComponentModel.BackgroundWorker。它是MS提供的托管线程类。它将在完成时通知您。一个选项是Thread.Join。这将使主线程等待子线程完成执行,然后再继续 另一个选项是查看System.ComponentModel.BackgroundWorker。它是由MS提供的托管线程类。它将在完成时通知您