I can start threads with switches but can't end them - c#

I want to start a number of threads based on the number of threads the computer running the program will have.
I tried doing switches but it seems that it can't end the threads.
This is my Main thread and doesn't work, it says the threads are out of context on the 2nd switch
Is there anything I can add or should I use a different method altogether?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Security.Principal;
namespace Yahtzee_DataMine
{
class Program
{
public static Random diceValue = new Random();
public static int numberOfDie = new int();
public static int numberOfSides = new int();
private static System.Object lockThis = new System.Object();
public static decimal percent = new decimal();
public static ConsoleColor oldColor = Console.ForegroundColor;
static void Main(string[] args)
{
while (true)
{
getInfo();
int processorCount = Environment.ProcessorCount;
Console.WriteLine(processorCount);
if (processorCount > 7) { processorCount = 7; }
switch (processorCount)
{
case 7:
Thread Rolls6 = new Thread(Rolling2);
Rolls6.Start();
goto case 6;
case 6:
Thread Rolls5 = new Thread(Rolling3);
Rolls5.Start();
goto case 5;
case 5:
Thread Rolls4 = new Thread(Rolling4);
Rolls4.Start();
goto case 4;
case 4:
Thread Rolls3 = new Thread(Rolling5);
Rolls3.Start();
goto case 3;
case 3:
Thread Rolls2 = new Thread(Rolling6);
Rolls2.Start();
goto case 1;
case 2:
case 1:
Thread Rolls1 = new Thread(Rolling7);
Rolls1.Start();
break;
}
while (true)
{
char quit = quit = Console.ReadKey().KeyChar;
if (quit == 'q')
{
Console.WriteLine("\rTerminated");
break;
}
}
switch (processorCount)
{
case 7:
Rolls6.abort();
goto case 6;
case 6:
Rolls5.abort();
goto case 5;
case 5:
Rolls4.abort();
goto case 4;
case 4:
Rolls3.abort();
goto case 3;
case 3:
Rolls2.abort();
goto case 1;
case 2:
case 1:
Rolls1.abort();
break;
}
}
}
public static void getInfo()
{
if (WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) == false)
{
Console.WriteLine("You Are Not Running With Elevated Administrative Access.");
Console.WriteLine("Please Restart And Run Program With Administrative Access");
}
#region gettingNumberOfDie
while (true)
{
Console.WriteLine("How Many Die Would You Like To Roll? Type Q To Quit");
String howManyDie = Console.ReadLine();
try
{
int.TryParse(howManyDie, out numberOfDie);
if (numberOfDie < 2)
{
Console.WriteLine("Please Enter A Integer Greater Than 1");
continue;
}
break;
}
catch
{
Console.WriteLine("Please Enter A Number Or Press Q To Quit");
continue;
}
}
#endregion
#region gettingNumberOfSides
while (true)
{
Console.WriteLine("How Many Sides Do You Want Each Die To Have?");
String howManySides = Console.ReadLine();
try
{
int.TryParse(howManySides, out numberOfSides);
if (numberOfSides < 2)
{
Console.WriteLine("Please Enter A Integer Greater Than 1");
continue;
}
break;
}
catch
{
Console.WriteLine("Please Enter A Number Or Press Q To Quit");
continue;
}
}
#endregion
#region gettingPercent
int percentCounter = 1;
percent = (1m / (numberOfSides));
decimal percentMultiplier = percent;
while (percentCounter < numberOfDie)
{
percent = percent * percentMultiplier;
percentCounter++;
}
percent = percent * 100;
#endregion
Console.WriteLine("With " + numberOfDie + ", " + numberOfSides + " Sided Die, You Have An " + percent + '%' + " Chance of Getting A Yahtzee With Any Given Roll");
Console.WriteLine("Press Any Key To Commence");
Console.ReadKey();
}
static int seed = Environment.TickCount;
static readonly ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));
public static int Rand()
{
return random.Value.Next(numberOfSides);
}
private static void Rolling1()
{
Console.WriteLine("Thread1 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll[counterYaht] != valuesOfRoll[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread1 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#endregion
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = (numberOfRolls).ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 1");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}
private static void Rolling2()
{
Console.WriteLine("Thread2 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll[counterYaht] != valuesOfRoll[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread2 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#endregion
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = numberOfRolls.ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 2");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}
private static void Rolling3()
{
Console.WriteLine("Thread3 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll3 = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll3.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll3[counterYaht] != valuesOfRoll3[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
#endregion
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread3 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = numberOfRolls.ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 3");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}
private static void Rolling4()
{
Console.WriteLine("Thread4 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll[counterYaht] != valuesOfRoll[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
#endregion
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread4 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = numberOfRolls.ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 4");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}
private static void Rolling5()
{
Console.WriteLine("Thread5 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll[counterYaht] != valuesOfRoll[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
#endregion
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread5 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = numberOfRolls.ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 5");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}
private static void Rolling6()
{
Console.WriteLine("Thread6 Started");
while (true)
{
#region rollS
Stopwatch rollTime = new Stopwatch();
rollTime.Start();
UInt64 numberOfRolls = 0;
while (true)
{
numberOfRolls++;
int counter = 0;
int[] valuesOfRoll = new int[numberOfDie];
#region Roll
while (counter < numberOfDie)
{
valuesOfRoll.SetValue((Rand() + 1), counter);
counter++;
}
#region isItYahtzee?
Boolean isItYahtzee = true;
int counterYaht = 1;
while (counterYaht < numberOfDie)
{
if (valuesOfRoll[counterYaht] != valuesOfRoll[0])
{
isItYahtzee = false;
counterYaht++;
break;
}
else
{
counterYaht++;
continue;
}
}
#endregion
if ((numberOfRolls % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread6 has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
#region ifYahtzee
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA = numberOfDie + "," + numberOfSides + "," + (numberOfDie * numberOfSides) + "," + numberOfRolls + "," + percent + "%" + "," + (percent * numberOfRolls) + "," + time + "," + timeSec + "," + (numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = numberOfRolls.ToString();
lock (lockThis)
{
System.IO.StreamWriter fileA = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\All.txt", true);
fileA.WriteLine(linesA);
fileA.Close();
System.IO.StreamWriter fileB = new System.IO.StreamWriter(Directory.GetCurrentDirectory().ToString() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", true);
fileB.WriteLine(linesB);
fileB.Close();
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread 6");
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
#endregion
#endregion
#endregion
}
}

It really looks like you need to learn some more of the basics of C# before you try something this complicated. You've got an interesting mix of really clever and very basic code. It appears that you've copy-and-pasted a lot from elsewhere.
The basic issue you're having is that you're declaring your thread variables (Thread Rolls6 = new Thread(Rolling2);) within the scope of the first switch (processorCount) statement. When it comes to the second one those variables don't exist. You could simply move the variable declarations higher up in the method to make them visible to both, but that's going to be a mistake. Calling Thread.Abort is a very bad practice. You really need something that lets the thread terminate normally.
In a nutshell your threads should look to see when they should end and they should respond accordingly.
The basic way this code looks is this:
private static void Rolling(CancellationToken ct)
{
while (true)
{
if (ct.IsCancellationRequested)
{
Console.WriteLine("Done with thread " + n);
break;
}
/* Do Stuff Here, But Let The Code Loop Back */
}
}
The code keeps checking the CancellationToken to see if IsCancellationRequested has been set or not.
That's how to end a thread cleanly.
Now I have gotten rid of all of those Rolling{n} methods and replaced them with a single method with the signature void Rolling(int n, int numberOfDie, int numberOfSides, double percent, CancellationToken ct). I've tried to get rid of global variables (which are generally bad) and I'm following the CancellationToken pattern.
To start up the threads I've gotten of the switch statements. The thread creation now looks like this:
CancellationTokenSource[] ctss =
Enumerable
.Range(1, processorCount)
.Select(n =>
{
var cts = new CancellationTokenSource();
var t = new Thread(() =>
Rolling(n, numberOfDie, numberOfSides, percent, cts.Token));
t.Start();
return cts;
})
.ToArray();
To cancel all of the threads the code just becomes:
foreach (var cts in ctss)
{
cts.Cancel();
}
...and then the ct.IsCancellationRequested becomes true in the Rolling method and they will shut down themselves.
That's the approach that you should be taking.
Here's your full code:
private static System.Object lockThis = new System.Object();
public static ConsoleColor oldColor = Console.ForegroundColor;
private static int seed = Environment.TickCount;
private static readonly ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));
static void Main(string[] args)
{
var x = GetValue("How Many Die Would You Like To Roll?", 1);
if (x.HasValue)
{
var y = GetValue("How Many Sides Do You Want Each Die To Have?", 2);
if (y.HasValue)
{
int numberOfDie = x.Value;
int numberOfSides = y.Value;
double percent = 100 * Math.Pow(1.0 / numberOfSides, numberOfDie);
Console.WriteLine("With " + numberOfDie + ", " + numberOfSides + " Sided Die, You Have An " + percent + '%' + " Chance of Getting A Yahtzee With Any Given Roll");
Console.WriteLine("Press Any Key To Commence");
Console.ReadLine();
int processorCount = System.Math.Min(Environment.ProcessorCount, 8);
Console.WriteLine(processorCount);
CancellationTokenSource[] ctss =
Enumerable
.Range(1, processorCount)
.Select(n =>
{
var cts = new CancellationTokenSource();
var t = new Thread(() =>
Rolling(n, numberOfDie, numberOfSides, percent, cts.Token));
t.Start();
return cts;
})
.ToArray();
while (true)
{
string quit = Console.ReadLine().Substring(0, 1).ToUpper();
if (quit == "Q")
{
Console.WriteLine(Environment.NewLine, "Terminated");
break;
}
}
foreach (var cts in ctss)
{
cts.Cancel();
}
}
}
}
private static int? GetValue(string prompt, int minimum)
{
while (true)
{
Console.WriteLine(prompt + " Type Q To Quit");
var input = Console.ReadLine().Substring(0, 1).ToUpper();
if (input == "Q")
{
return null;
}
int output;
if (int.TryParse(input, out output))
{
if (output < minimum)
{
Console.WriteLine("Please Enter an Integer Greater Than Or Equal To " + minimum);
continue;
}
else
{
return output;
}
}
}
}
private static void Rolling(int n, int numberOfDie, int numberOfSides, double percent, CancellationToken ct)
{
Console.WriteLine("Thread" + n + " Started");
Stopwatch rollTime = Stopwatch.StartNew();
long numberOfRolls = 0;
while (true)
{
if (ct.IsCancellationRequested)
{
Console.WriteLine("Done with thread " + n);
break;
}
int[] valuesOfRoll =
Enumerable
.Range(0, numberOfDie)
.Select(x => random.Value.Next(numberOfSides) + 1)
.ToArray();
Boolean isItYahtzee = valuesOfRoll.All(x => x == valuesOfRoll[0]);
if ((numberOfRolls++ % 100000000) == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Thread" + n + " has rolled " + numberOfRolls);
Console.ForegroundColor = oldColor;
}
if (isItYahtzee == true)
{
rollTime.Stop();
string time = rollTime.Elapsed.ToString();
string timeSec = rollTime.Elapsed.TotalSeconds.ToString();
string linesA =
String.Format(
"{0},{1},{2},{3},{4}%,{5},{6},{7},{8}",
numberOfDie,
numberOfSides,
numberOfDie * numberOfSides,
numberOfRolls,
percent,
percent * numberOfRolls,
time,
timeSec,
numberOfRolls / rollTime.Elapsed.TotalSeconds);
string linesB = (numberOfRolls).ToString();
lock (lockThis)
{
File.AppendAllLines(Directory.GetCurrentDirectory() + "\\All.txt", new[] { linesA });
File.AppendAllLines(Directory.GetCurrentDirectory() + "\\Avg_" + numberOfDie + "X" + numberOfSides + ".txt", new[] { linesB });
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(numberOfRolls + " File Has Been Successfully Save By Thread " + n);
Console.ForegroundColor = oldColor;
numberOfRolls = 0;
break;
}
}
}

Related

How can I check to see if the user won? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to check to see if user won with a conditional?
int score1 = 0;
int score2 = 0;
int score3 = 0;
for (int i = 1; i < 11; i++)
{ //open for
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
This is the piece of code I am referring to.
So, to solve the problem, you need 3 variables to which we add the various scores at each lap, this variables are then compared before the end of the while loop. The code posted shows only the comparison for the first option. I'm sure you can figure out how to compare for the remaining options.
class Program
{
public static void Main(string[] args)
{ //open main method
string name1 = "Buck";
int endurance1 = 6;
int speed1 = 4;
string name2 = "Daisy";
int endurance2 = 4;
int speed2 = 6;
string name3 = "Leo";
int endurance3 = 7;
int speed3 = 3;
int balance = 100;
Console.WriteLine("Welcome to the racetrack!\nToday's races will include 10 laps for reach race. There will be 3 races today. \nYou have $100 you can choose to bet on one of our 3 horses.\n1. Bet on a horse. \n2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{ //open while1
Console.WriteLine("Would you like to bet on: \n1." + name1 + ": \nEndurance:" + endurance1 + "\nSpeed:" + speed1 + "\n2." + name2 + ": \nEndurance:" + endurance2 + "\nSpeed:" + speed2 + "\n3." + name3 + ":\nEndurance:" + endurance3 + "\nSpeed:" + speed3 + "\nPlease enter the name of the horse as it appears on the screen.");
string choice = Console.ReadLine();
if (choice == "Buck")
{
Console.WriteLine("You have chosen " + name1 + ".");
}
else if (choice == "Daisy")
{
Console.WriteLine("You have chosen " + name2 + ".");
}
else
{
Console.WriteLine("You have chosen " + name3 + ".");
}
Console.WriteLine("How much would you like to bet? Your current balance is $" + balance + ".");
string money = Console.ReadLine();
int bet = int.Parse(money);
Console.WriteLine("You are betting $" + bet + " on " + choice + ". Type \'start\' to start the race.");
string race = Console.ReadLine();
int totalScore1 = 0;
int totalScore2 = 0;
int totalScore3 = 0;
if (race == "start")
{ // open if
Console.WriteLine("Let the races begin!");
for (int i = 1; i < 11; i++)
{ //open for
System.Random r = new System.Random();
int score1 = speed1 + endurance1 + r.Next(1, 8);
int score2 = speed2 + endurance2 + r.Next(1, 8);
int score3 = speed3 + endurance3 + r.Next(1, 8);
totalScore1 += score1;
totalScore2 += score2;
totalScore3 += score3;
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
else
Console.WriteLine("Okay, take your time.");
if(totalScore1> totalScore2 && totalScore1 > totalScore3 && choice =="Buck")
{
Console.WriteLine("Buckl won the race");
}
} //close while
Console.WriteLine("Aw, too bad. Thanks for joining us!");
} //close main method
}
}
Instead of solving your exact issue, I'd like to show you the power of collections (arrays and Dictionary). They allow you not to manually type every single condition for a single horse (imagine if you had 15 horses)
Since you're a novice, you probably will have hard time understanding this code, but watch and learn!
using System;
using System.Collections.Generic;
struct Horse
{
public string name;
public int endurance;
public int speed;
};
class Program {
public static void Main(string[] args)
{
var horseByName = new Dictionary<string, Horse>
{
{"Buck", new Horse{ name = "Buck", endurance = 6, speed = 4 } },
{"Daisy", new Horse{ name = "Daisy", endurance = 6, speed = 4 } },
{"Leo", new Horse{ name = "Leo", endurance = 7, speed = 3 } },
{"Maya", new Horse{ name = "Maya", endurance = 5, speed = 4 } },
{"Richard", new Horse{ name = "Richard", endurance = 5, speed = 4 } },
};
int balance = 100;
int numberOfHorses = horseByName.Count;
Console.WriteLine("Welcome to the racetrack!");
Console.WriteLine("Today's races will include 10 laps for reach race. There will be 3 races today.");
Console.WriteLine("You have $100 you can choose to bet on one of our 3 horses.");
Console.WriteLine("1. Bet on a horse.");
Console.WriteLine("2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{
Console.WriteLine("Would you like to bet on:");
int horseNumber = 1;
foreach (var horse in horseByName.Values)
{
Console.WriteLine($"{horseNumber}. {horse.name}\nEndurance: {horse.endurance}\nSpeed: {horse.speed}");
++horseNumber;
}
string choice = Console.ReadLine();
while (!horseByName.ContainsKey(choice))
{
Console.WriteLine("We don't have such horse, try again:");
choice = Console.ReadLine();
}
Console.WriteLine($"You have chosen {choice}.");
Console.WriteLine($"How much would you like to bet? Your current balance is ${balance}.");
int bet = int.Parse(Console.ReadLine());
Console.WriteLine($"You are betting ${bet} on {choice}. Type \'start\' to start the race.");
string race = Console.ReadLine();
if (race == "start")
{
Console.WriteLine("Let the races begin!");
int[] scores = new int[numberOfHorses];
int maxScorePerLap = 0;
string maxScoredHorseName = "";
for (int lap = 1; lap < 11; lap++)
{
System.Random r = new System.Random();
int horseId = 0;
foreach (var horse in horseByName.Values)
{
scores[horseId] = horse.speed + horse.endurance + r.Next(1, 8);
if (scores[horseId] > maxScorePerLap)
{
maxScorePerLap = scores[horseId];
maxScoredHorseName = horse.name;
}
++horseId;
}
Console.WriteLine($"{maxScoredHorseName} takes the lead in lap {lap}!");
}
if (maxScoredHorseName == choice)
{
Console.WriteLine($"Hurray! {choice} won!");
balance += bet;
}
else
{
Console.WriteLine($"Unfortunately {maxScoredHorseName} won, but you had bet on {choice}...");
balance -= bet;
}
}
else
{
Console.WriteLine("Okay, take your time.");
}
}
Console.WriteLine("Aw, too bad. Thanks for joining us!");
}
}

C# By Pressing button do in background

Can someone explain me how can i do async tasks from this code?
Currently code does work and do the job but i have tried to make it async? So app will not get frozen while its executing but no success.
public WebpageLocalScanner()
{
InitializeComponent();
InitializeListView();
}
internal string GetType(string ip, int port)
{
try
{
if (port == 1234 || port == 4321)
{
string urlAddress = string.Format("http://{0}", ip);
string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
if (text.Contains("<HTML>"))
{
return "Webpage is here";
}
}
}
catch (Exception)
{
}
return string.Empty;
}
public void AddItem() {
listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
for (int i = froms1b; i <= tos1b; i++)
{
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetType(GenIP, p);
if (result != null) {
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
};
}
}
}
}
}
private void InitializeListView()
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
// listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
// Attach Subitems to the ListView
listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
}
private void button1_Click(object sender, EventArgs e)
{
AddItem();
}
What im really struggle is understand how can i convert each function to return and can be used in background if its called.
Whatever i try its getting missing something.
Can you able to make it more clear for me?
What this does is simply scan local network to find current ip of webserver on other pc.
But 255 ips to do it takes a while and app just hungs and have to wait till its finished?
ANSWER CODE APPLIED:
public async void AddItem()
{
//listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
//var listViewItems = new List<ListViewItem>();
await Task.Run(() =>
{
for (int i = froms1b; i <= tos1b; i++)
{
List<string[]> rows = new List<string[]>();
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetProxyType(GenIP, p);
if (result != "")
{
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
var listViewItem = new ListViewItem(row);
if (listView1.InvokeRequired)
{
listView1.Invoke(new MethodInvoker(delegate
{
listView1.Items.Add(listViewItem);
//row.Checked = true;
}));
}
else
{
listView1.Items.Add(listViewItem);
listViewItem.Checked = true;
}
//string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
//listViewItems.Add(row);
//listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
};
}
}
}
});
}
}
private async void button1_Click(object sender, EventArgs e)
{
AddItem();
}
You use the async keyword on any method that will need to run asynchronously. You use await on the code that you want to run in the background. Await yields control back to the UI until that code finishes. You only use async on methods that have an await, and you only use await on code that returns a Task. If you have code that you need to run in the background and it doesn't return a Task, you can wrap it in a Task.Run.
I think this will work, but I haven't tested it.
public WebpageLocalScanner()
{
InitializeComponent();
InitializeListView();
}
internal string GetType(string ip, int port)
{
try
{
if (port == 1234 || port == 4321)
{
string urlAddress = string.Format("http://{0}", ip);
string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
if (text.Contains("<HTML>"))
{
return "Webpage is here";
}
}
}
catch (Exception)
{
}
return string.Empty;
}
public async void AddItem() {
listView1.Items.Clear();
int froms192 = Convert.ToInt32(tB1.Text);
int froms168 = Convert.ToInt32(tB2.Text);
int froms1a = Convert.ToInt32(tB3.Text);
int froms1b = Convert.ToInt32(tB4.Text);
int fromports = Convert.ToInt32(tBp1.Text);
int toports = Convert.ToInt32(tBp2.Text);
string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
int FromPort = fromports;
int ToPort = toports;
int tos192 = Convert.ToInt32(tB5.Text);
int tos168 = Convert.ToInt32(tB6.Text);
int tos1a = Convert.ToInt32(tB7.Text);
int tos1b = Convert.ToInt32(tB8.Text);
string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
if (froms1a < tos1a || froms1b < tos1b)
{
var rows = new List<string[]>();
await Task.Run(() => {
for (int i = froms1b; i <= tos1b; i++)
{
for (int u = froms1a; u <= tos1a; u++)
{
for (int p = fromports; p <= toports; p++)
{
string GenIP = froms192 + "." + froms168 + "." + u + "." + i;
string result = GetType(GenIP, p);
if (result != null) {
string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
rows.add(row);
};
}
}
}
});
listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
}
}
private void InitializeListView()
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
// listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
// Attach Subitems to the ListView
listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
}
private async void button1_Click(object sender, EventArgs e)
{
AddItem();
}

C# having problems with using global variables

So, I have finished majority of my code but one criteria required me to use a Procedure. So, when i decided to use a procedure i encountered several of problems. The main issue was that the variables which i have included in the first method(Generate Number and number) wont show up in my other methods.So can i make these variables global so that they work in all of my methods or is there another alternative solution to this problem?
Note: This is not my full code its just a piece out of it.
class Program
{
static void Main(string[] args)
{
Random GenerateNumber = new Random();
int[] number = new int[6];
Generating();
Ordering();
}
static void Generating()
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = GenerateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c] + "\n");
}
}
}
static void Ordering()
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}
Make them global is easiest but as said above, not the best way.
class Program
{
static Random GenerateNumber = new Random();
static int[] number = new int[6];
static void Main(string[] args)
{
Generating();
Ordering();
}
Better to use parameters
class Program
{
static void Main(string[] args)
{
Random GenerateNumber = new Random();
int[] number = new int[6];
Generating(GenerateNumber, number);
Ordering(number);
}
static void Generating(Random generateNumber, int[] number)
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = generateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c] + "\n");
}
}
}
static void Ordering(int[] number)
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}
If you have more methods like those working with your array of numbers then I'd suggest you create a CLASS that encapsulates the behaviors that you want. Something alone the lines of:
public class MyNumberArrayWithMethods
{
public int[] Numbers { get; set; }
public Action<int, int> Writer { get; set; }
//parametric constructor
public MyNumberArrayWithMethods(int length, Action<int, int> writer = null)
{
Numbers = new int[length];
Writer = writer;
}
public void Generating(int lowerBound = 1, int upperBound = 50)
{
for (int c = 0; c < Number.Length; c++)
{
if (Number[c] == 0)
{
Number[c] = GenerateNumber.Next(lowerBound, upperBound);
if(Writer != null)
Writer(c, Number[c])
}
}
}
public void Ordering()
{
Console.Clear();
Array.Sort(Number);
if(Writer != null)
for (int i = 0; i < Number.Length; i++)
Writer(i, Number[i]);
}
//... all other methods that work with "Number" array should go here
}
and then in your main
static void Main(string[] args)
{
Action<int, int> writer =
(pos, num) => { Console.Write("Number " + (pos + 1) + " = " + num + "\n"); }
var MyCtrl = new MyNumberArrayWithMethods(6, writer);
MyCtrl.Generating();
Ordering();
}
Please notice how I moved your Array.Sort call outside the loop. If you leave it inside you will sort the array as many times as the length of the array and I'm guessing you don't want that.
You could do it like this
class Program
{
public static void Main(string[] args)
{
Program p = new Program();
Random GenerateNumber = new Random();
int[] number = new int[6];
int[] generatedNumber = p.Generating(GenerateNumber, number);
p.Ordering(generatedNumber);
}
public int[] Generating(Random GenerateNumber, int[] number)
{
Console.Clear();
Console.WriteLine("Stage 1 : 6 random numbers have been
generated:\n");
for (int c = 0; c < number.Length; c++)
{
if (number[c] == 0)
{
number[c] = GenerateNumber.Next(1, 50);
Console.Write("Random number " + (c + 1) + " = " + number[c]
+ "\n");
}
}
return number;
}
public void Ordering(int[] number)
{
Console.Clear();
for (int i = 0; i < number.Length; i++)
{
Array.Sort(number);
Console.Write("Number " + (i + 1) + " = " + number[i] + "\n");
}
}
}
https://dotnetfiddle.net/3K6P54

C# How to make an open while loop that stops when user wants

I'm writing a small loop in C# that I want to stay open until the user specifies.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
while (goon == " ")
{
Console.WriteLine("Enter a score");
score += int.Parse(Console.ReadLine());
Console.WriteLine(score + " " + counter);
counter++;
}
}
I know this code is not correct.
One way would be to set goon to something other than " " if anything other than an integer is entered by the user.
The easiest way to check if an integer has been entered is by using the Int32.TryParse method.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
int userInput = 0;
bool isInt = true;
while (goon == " ")
{
Console.WriteLine("Enter a score");
isInt = Int32.TryParse(Console.ReadLine(), out userInput);
if(isInt)
{
score += userInput;
Console.WriteLine(score + " " + counter);
counter++;
}
else
{
goon = "exit";
}
}
}
public void ScoreCalc()
{
int counter = 1;
int score = 0;
String input;
while (true)
{
Console.WriteLine("Enter a score");
input=Console.ReadLine();
if(input != "end"){
score += int.Parse(input);
Console.WriteLine(score + " " + counter);
counter++;
}else{
break;
}
}
}
I've updated your method assuming "quit" text as an exit signal from the user to break the while loop. Hope this helps!
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
var userInput = string.Empty;
var inputNumber = 0;
const string exitValue = "quit";
while (goon == " ")
{
Console.WriteLine("Enter a score or type quit to exit.");
userInput = Console.ReadLine();
if (userInput.ToLower() == exitValue)
{
break;
}
score += int.TryParse(userInput, out inputNumber) ? inputNumber : 0;
Console.WriteLine(score + " " + counter);
counter++;
}
}

Testing all cells in datagridview

for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}
Shouldn't that be? Since you yourself adding rows to your gridview by calling Add() method as can be seen in your posted code
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(),
No idea since I don't know your requirement but to me it feels like you wanted to have the other part as else block.
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}

Categories

Resources