views:

92

answers:

5

In my windows application i have a usercontrol, which in turn host few other usercontrols.

Just before the end of the main user control's constructor, i try to create a thread... but it does not appear to be created:

mainUserControl()
{
   var t=new Thread(ThreadJob);
   t.IsBackground=true;
   t.Start();
}


private void ThreadJob() 
{
   //Thread.Sleep(120000);
   //if(txtStatus.InvokeRequired) {
   //  txtStatus.Invoke(new MethodInvoker(delegate { txtStatus.Text="Thread started"; }));
   //}

   txtStatus.Text="sample";
 }

This code does not work: i take this as evidence that the thread is not spawned, as if it were then txtStatus.Text="sample"; would have thrown an exception.... right?

So what's happening here? Why isn't my thread being created?

+1  A: 

Background threads don't have access to UI thread created components generally. My suggestion is add a try catch to the ThreadJob, but best of all is to use a BackgroundWorker instead as this has been designed to access UI thread components directly (well, using unseen magic :-)

Preet Sangha
+3  A: 

It would not necessarily have thrown an exception. It might have, but then again it might have just failed to work. There's a reason why cross-thread UI access is discouraged: it's flaky and dangerous. Overall, not a good way to verify your program is set up the way you think it should be.

Use a breakpoint and a debugger...

Shog9
Or a Debug.WriteLine which will appear in the output window of VS.
Richard
@Richard: yeah, that's good too.
Shog9
+1  A: 

My guess is, since you took out your delay, the thread is spawning, setting the value, and shutting down.

Accessing txtStatus.Text from the wrong thread is not guaranteed to throw, though. There are situations where you can access a property on a control from a background thread and it will not throw. (You still shouldn't do it, though!)

If you still believe the thread is not starting, you could try setting a breakpoint there - I'm fairly certain you'll see that it's hitting that point.

Reed Copsey
A: 

That a Forms threading exception was not thrown is not good evidence your thread didn't run. Slightly better way to verify your thread running: Replace the assignment with a Console.Out.WriteLine("sample") and then check your console output.

Not Sure
A: 

Are you not supposed to use the ThreadStart object?

As in:

Thread t = new Thread(new ThreadStart(ThreadJob));

I use the ThreadStart and ParamatizedThreadStart objects without issue, all the time. You should definately not being accessing the UI objects created in the other thread, unless you've disabled this exception, it should be thrown, as you correctly state, if your above thread is working as expected.

David

David