Hi,
I have done a test using the lock(lockobject), which will be an interesting question.
I have created 2 background threads, that I start simultaniously. Threads uses a while(true) loop to produce the test.
If we uncomment and use the lock(lockobject) in the code. None of the loops will write values to any file. However if we doesn´t use the lock(lockobject) in the code. Values will be written to the file.
Tests goes for 2 scenarios(String or bool)
if (stringTest != "Test1" && stringTest != "Test2")
if (boolTest != true && boolTest != false)
When values are written to file(when we doesn´t use the lock(lockobject). Any of those will be written to file:
* "Test1"
* "Test2"
* "True"
* "False"
My question is what exactly is happening. How can values be written to file when not using the lock(lockobject).
Question
if (stringTest != "Test1" && stringTest != "Test2") ----> "Test1" or "Test2" is written to file anyway?
if (boolTest != true && boolTest != false) ----> "True" or "False" is written to file anyway?
bool hasStarted = false;
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
if (hasStarted == false)
{
Thread thread1 = new Thread(backgroundthread1); thread1.Start();
Thread thread2 = new Thread(backgroundthread2); thread2.Start();
hasStarted = true;
}
}
object lockObject = new object();
bool boolTest = false;
String stringTest = "";
void backgroundthread1()
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
while (true)
{
//lock (lockObject)
//{
boolTest = false;
stringTest = "Test1";
//if (stringTest != "Test1" && stringTest != "Test2")
if (boolTest != true && boolTest != false)
{
FileStream stream = new FileStream("C:/Test1.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(boolTest + "," + stringTest);
writer.Close(); stream.Close();
}
//}
}
}
void backgroundthread2()
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
while (true)
{
//lock (lockObject)
//{
boolTest = true;
stringTest = "Test2";
//if (stringTest != "Test1" && stringTest != "Test2")
if (boolTest != true && boolTest != false)
{
FileStream stream = new FileStream("C:/Test2.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(boolTest + "," + stringTest);
writer.Close(); stream.Close();
}
//}
}
}