views:

44

answers:

4

Hello,

I have a lot of long-running activities and think that spawning this activity off to another thread will be a good way to have my U.I be able to update to show its current status.

However, when I use the following:

Thread t = new Thread(() =>
{
   /* do magic here */
});

Nothing inside the foreach loop that's inside the thread gets done. But, when I don't use a thread, the work does get done, so I know it's not a problem with the loop.

Any suggestions?

+1  A: 

Are you even starting the thread?

newThread.Start();

In the sample you provide you merely declare it.

Also bear in mind that if you're using WinForms, you won't be able to update the UI directly from any thread other than the one that created it; for example, modifying a progress bar or label control from within your foreach loop.

nukefusion
Sorry that was my stupid mistake. I forgot to type t.Start in the question, it is actually in my program though. +1 anyway for pointing it out!
lucifer
+1  A: 

You need to start the tread, t.Start();

Creating the instance just creates an managed wrapper for a thread. Calling Start will set things in motion and eventually make your code run on a separate thread.

Brian Rasmussen
Sorry that was my stupid mistake. I forgot to type t.Start in the question, it is actually in my program though. +1 anyway for pointing it out!
lucifer
@j-t-s: Okay then, could I ask you to give us additional details then. It isn't clear to me how you determine that the thread isn't running then.
Brian Rasmussen
+1  A: 

Probably you haven't started the thread, so its not running yet.

However, in your case its usually better to use BackgroundWorker class, this will create the thread for you and provide thread-safe way to update the UI with the progress of the threads work.

Grzenio
Sorry that was my stupid mistake. I forgot to type t.Start in the question, it is actually in my program though. +1 anyway for pointing it out!
lucifer
+2  A: 

You may also want to take a look at BackgroundWorker as it nicely encapsulates everything.

Daniel Frear
Thanks djfrear.
lucifer