views:

49

answers:

2

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" 

});
    }
+1  A: 

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 InitValues method ends, so will the thread.

If the InitValues method is brief, perhaps consider ThreadPool, but otherwise; leave it.

You might want to consider adding some exception handling, so that if InitValues throws it doesn't kill the entire AppDomain, 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 procedural Rows.Add is just illustrative).

Marc Gravell
thanks a lot Sir Marc.
yonan2236
ok sir, I will note your advices.
yonan2236
A: 

One option is Thread.Join. This will make the main thread wait for the child thread to complete execution before continuing.

Another option is look into the System.ComponentModel.BackgroundWorker. It is a managed threading class provided by MS. It will notify you when it is complete.

TerrorAustralis
oh yes, I read about that, thanks...
yonan2236