I wrote a small computer game where you can mine gold. The game is used to understand asynchronous programming with async and await. The loop menu offers three options: Mine gold, view evaluation, and exit.
The GoldMining method makes heavy use of the CPU. The probability to get one gram of gold during a mining is 1 in 10.000.000. Therefore it takes a long time until 1000g of gold are mined.
You start mining gold asynchronously from the loop menu. Then you can use option 2 (show evaluation) at any time to see the amount of gold you have mined so far.
Although the GoldMining method is very time consuming, the loop menu does not freeze. That's nice. However, I call the asynchronous method GoldMining without await. Now my question: Is this way of calling asynchronous methods to prevent the program from freezing a recommended approach?
//Evaluation contains the gold stock that was mined in total.
//The class definition is done at the very bottom.
Evaluation evaluation = new Evaluation();
await Main(evaluation);
static async Task Main(Evaluation evaluation){
string input="start";
while(input!="exit"){
Console.WriteLine("choose an option:");
Console.WriteLine("1 gold mining");
Console.WriteLine("2 show evaluation");
Console.WriteLine("3 exit.");
input=Console.ReadLine();
switch(input){
//Call GoldMining without await
case "1":GoldMining(evaluation);break;
case "2":Console.WriteLine(evaluation.gold);;break;
case "exit":input="exit"; break;
default:input="exit";break;
}
}
}
static async Task GoldMining(Evaluation evaluation){
Random rand= new Random();
int yield=0;
Console.WriteLine("Gold mining begins");
await Task.Run(() =>
{
while(yield<1000){
int chance =rand.Next(0,10000000);
if(chance==1){yield++;evaluation.gold++;}
} 2
});
Console.WriteLine("1000g Gold minded");
}
public class Evaluation{
public int gold{get;set;}
public Evaluation(){
this.gold=0;
}
}