I have programmed a bulb production simulation in C#. When a user enters option 1 in the command line interface an asynchronously function starts simulating the production of 10,000 bulbs whereby 5% of bulbs are defect. If a defect bulb is detected, an observer will be notified and display a message in the command prompt. I have noticed that the keyword await if it is placed directly before prod.startMaschine(maschineID);
causes the program to not work anymore. So I have removed it. I wonder now when to use await and when not to. Can you explain it with my example program?
Console.WriteLine("Bulb Production Monitoring!");
Main();
static async Task Main() {
string input = "";
int maschineID = 1;
Production prod = new Production();
Console.WriteLine("1: starts a production maschine");
Console.WriteLine("2: exits the production process");
while(!input.Equals("exit")) {
input=Console.ReadLine();
switch(input) {
case "1":
prod.registerObserver(new Observer());
prod.startMaschine(maschineID);
maschineID++;
break;
case "2" :
input="exit"; break;
default:
break;
}
}
}
public class Bulb {
public bool _functionTest;
}
public class Production {
private List<Observer> _observerList = new List<Observer>();
public async Task startMaschine(int maschineId) {
Console.WriteLine($"Maschine {maschineId} is ready for use ... ");
int i=0;
Random rndGenerator = new Random();
await Task.Run(
async ()=> {
while(i<10000) {
int rndNumber=rndGenerator.Next(1,101);
Bulb bulb = new Bulb();
await Task.Delay(2000);
if (rndNumber<=5) {
bulb._functionTest=false;
this.notify(maschineId);
}
else {
bulb._functionTest=true;
}
}
}
);
}
public void registerObserver(Observer obs) {
_observerList.Add(obs);
}
private void notify(int maschineId) {
foreach(Observer obs in _observerList) {
obs.update(maschineId);
}
}
}
public class Observer {
public void update(int maschineId) {
DateTime localDate = DateTime.Now;
Console.WriteLine($"Defect bulb identified on maschine {maschineId} at {localDate}.");
}
}