I am fairly new to threading in general and i want to try it in C#. I am trying to make a basic simulation of tonnage of something which is decaying every 20 seconds and being refilled every 10 seconds. From what i read, thread safety is something i need to consider as there are two threads; one for decaying the variable tonnage by 160, one for adding a random amount to the tonnage and since they are making transactions to the variable tonnage, i should make sure they are accessed correctly.
I read on how to use lock(object) and i understand the concept for simple thread examples but how do i use it for 2 threads running forever and have to make timely adjustments in the tonnage?
Here is what i have, but when i lock the whole loop, the other thread never spawns. Or do i have the wrong code structure?
public double tonnage = 1000;
private object x = new object();
//Starts the simulation, runs forever until user ends the simulation
private void btnStart_Click(object sender, EventArgs e)
{
//Decay Tonnage
Thread decayTonnageThread = new Thread(() => decayTonnage (tonnage));
decayTonnageThread .Start();
//Add Tonnage
Thread addTonnageThread = new Thread(() => addTonnage (tonnage));
addTonnageThread .Start();
}
//I want to decay the tonnage every 20 seconds
public void decayTonnage (double tonnage)
{
lock(x)
{
while (true)
{
tonnage = tonnage - 160;
Thread.Sleep(20000);
}
}
}
//Add to the tonnage every 10 seconds
public void addTonnage (double tonnage)
{
lock(x)
{
while (true)
{
Random random = new Random();
double randomNumber = random.Next(97, 102);
tonnage = tonnage + randomNumber;
Thread.Sleep(10000);
}
}
}