You can create as many threads as you like:
ThreadStart printIntegerStart = new ThreadStart(PrintInteger);
Console.WriteLine("Starting thread...");
Thread printIntegerThread = new Thread(printIntegerStart);
printIntegerThread.Start();
Thread printIntegerThread2 = new Thread(printIntegerStart);
printIntegerThread2.Start();
Thread printIntegerThread3 = new Thread(printIntegerStart);
printIntegerThread3.Start();
Create a method public static void LoadData()
which simulates loading resources by printing progress from Thread.Sleep()
method to wait
Create a main loop where each time the user presses enter, the LoadData()
method is executed on a separate thread.
static async Task<int> MyMethodAsync()
{
byte[] content = await client.GetByteArrayAsync("https://docs.microsoft.com/en-us/");
return content.Length;
}
Task<int> myMethodResult = MyMethodAsync();
class Program
{
static async Task<string> GetResultAsync()
{
int waitTime = 5000;
await Task.Delay(waitTime);
// Replace this with your time consuming async functionality
return new string(
$"The task took {waitTime / 1000} seconds to finish."
);
}
static void Main(string[] args)
{
Console.WriteLine("Starting operation...");
Task<string> resultTask = GetResultAsync();
Console.WriteLine("Operation has been started.");
Console.WriteLine("In the meantime, tell me something nice: ");
string somethingNice = Console.ReadLine();
resultTask.Wait(); // Wait for the task to complete
Console.WriteLine(resultTask.Result);
Console.ReadKey();
}
}
Re-create the exercise 2, but instead of using separate threads for "loading the data", use an asynchronous method LoadDataAsync()