text.Append("second thread \n"+i.ToString() + " ");
}
}
}
}
}
here when I have iteration which is small numbers then it works fine with LOCK.
But as loop is for larger value which is in the code,then output varies at times it shows only First thread or only second thread wherein again
numbers displayed are not as per given in the loop.It skips many numbers and it is very unpredictable output.Can anyone explain correctly.
why it is the case..Should I Use Monitor class instead....
Member
44 Points
193 Posts
Lock keyword not working properly
Nov 28, 2014 07:17 AM|srm2009|LINK
I have written a code which is as below:I am not able to understand the out as I get output different.
The code:
class Class6
{
static StringBuilder text = new StringBuilder();
public static void Main()
{
Thread firstThread = new Thread(new ThreadStart(Fun1));
Thread secondThread = new Thread(new ThreadStart(Fun2));
firstThread.Start();
secondThread.Start();
firstThread.Join();
secondThread.Join();
Console.WriteLine("Text is:\r\n{0}", text.ToString());
}
public static void Fun1()
{
lock(text)
{
for(int i=1; i<=200; i++)
{
Thread.Sleep(10);
text.Append("First Threadd \n "+i.ToString() + " ");
}
}
}
public static void Fun2()
{
lock(text)
{
for(int i=21; i<=400; i++)
{
Thread.Sleep(2);
text.Append("second thread \n"+i.ToString() + " ");
}
}
}
}
}
here when I have iteration which is small numbers then it works fine with LOCK.
But as loop is for larger value which is in the code,then output varies at times it shows only First thread or only second thread wherein again
numbers displayed are not as per given in the loop.It skips many numbers and it is very unpredictable output.Can anyone explain correctly.
why it is the case..Should I Use Monitor class instead....
Thanks in advance
All-Star
37441 Points
9076 Posts
Re: Lock keyword not working properly
Nov 28, 2014 07:51 AM|AidyF|LINK
The buffer in your console is probably just not set to store all the lines you need. Write it to the debug output and look at that instead