views:

145

answers:

2

Hello.

I'm developing a Windows Mobile 5.0 and above application using .Net Compact Framework 2.0 SP2 and C#.

How can I know when a thread ends?

This is my code:

System.Threading.Thread thread1 =
    new System.Threading.Thread(() => RetreiveSoMuchData(ID));
thread1.Start();

Thank you.

+1  A: 

Since you're spawning your own thread, as soon as RetrieveSoMuchData(..) finishes, the thread will terminate.

You can notify yourself of this by using an EventWaitHandle, such as a AutoResetEvent.

Reed Copsey
AutoResetEvent will block the application?
VansFannel
AutoResetEvent will block (if you're waiting on the event) until you call Set on it.
Reed Copsey
+3  A: 

You'll need to get the thread to:

  • Fire an event that someone is listening to
  • Set a value someone else is checking
  • Set a wait event that another thread is waiting on (e.g. a AutoResetEvent or ManualResetEvent)
  • Return on an infinite join() command (on that thread)

Unfortunately neither of these leaves the thread alone or doesn't pull in other threads, but this is the joy of multithreading. I'd generally go for firing an event myself. The BackgroundWorker object in the Full Framework does this but unfortunately is not available in CF so you'll have to write that yourself (perhaps write a wrapper for the Thread class that does this for you).

Quibblesome
Two questions: if I fire a event, this event it will be run on this thread or in the primary thread. The second question is about your third posibiliy: the AutoResetEvent will block the application?
VansFannel
If you fire the event it will be on the background thread. If you're planning to update the UI you will have to marshal back to the UI thread via .Invoke() or BeginInvoke(). If you wait on a handle you will need to either lock the UI thread up on this wait (not recommended) or have a further thread that is waiting on this event. However in that latter case you will still have the marshalling issue if you wanna touch the UI. The other alternative is to have the UI thread poll a value (say a bool) on a timer that the background thread updates when it is done (then you don't need any marshaling)
Quibblesome
I'd personally still go for the event firing plus marshalling myself.
Quibblesome
I think so, but I'm getting problems with a control that I've created on the background thread and the sentence this.Controls.Add(threadControl).
VansFannel
oOo no. Don't create a control on the background thread. Keep the controls as is. Then when the background thread is planning to update the controls make it call BeginInvoke() or Invoke() instead. You can pass in a function pointer (delegate). In that delegate update the UI normally. Then everything will work.
Quibblesome
Yeah! It works!!! I've used a delegate to create the objects and it works!! Thank you very much.
VansFannel