thread program.....................

Posted by Anand under C# on 2/29/2012 | Points: 10 | Views : 774 | Status : [Member] | Replies : 2
can someone please explain me this program the output is
Done but it is being printed only once
it should b printing Done twice
its not my program this was thought in our class today

using System;
using System.Threading;


class ThreadTest
{
bool done;

static void Main()
{
ThreadTest tt = new ThreadTest(); // Create a common instance
new Thread (tt.Go).Start();
tt.Go();
}

// Note that Go is now an instance method
void Go()
{
if (!done) { done = true; Console.WriteLine ("Done"); }
}
}

-


Responses

Posted by: Hmanjarawala on: 2/29/2012 [Member] Bronze | Points: 25

Up
0
Down
Hi this because, you have put condition on done which is global variable.
write your code like:

using System;
using System.Threading;


class ThreadTest
{
bool done;

static void Main()
{
ThreadTest tt = new ThreadTest(); // Create a common instance
new Thread (tt.Go).Start();
done=false;
tt.Go();
}

// Note that Go is now an instance method
void Go()
{
if (!done) { done = true; Console.WriteLine ("Done"); }
}
}


Himanshu Manjarawala
Sr. Software Engineer@AutomationAnywhere
http://fieredotnet.wordpress.com/

Anand, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Anand on: 3/1/2012 [Member] Starter | Points: 25

Up
0
Down
OK sir its showing mean error object reference not set to an instance variable
and sir can u sir can u me small example on Locks in thread c# :)

-

Anand, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response