With the code below, how will I know if my thread is already done doing tasks? My purpose is to kill that thread in order to free memory. Or how should I do it?
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"
});
}
Never abort a thread unless your process is terminally sick and is going to die anyway. Very bad things happen (for example, irretrievable locks). The code is fine as is. When the
InitValuesmethod ends, so will the thread.If the
InitValuesmethod is brief, perhaps considerThreadPool, but otherwise; leave it.You might want to consider adding some exception handling, so that if
InitValuesthrows it doesn’t kill the entireAppDomain, and you should understand that most of the time here is going to be spent updating the UI on the UI thread (unless your table is being populated from an external source, and the proceduralRows.Addis just illustrative).