'C# Proper multitasking
I have simple console app which handles some time consuming routine using tasks. While task is running Console shows the user some string indicating that job is being processed. The following code works pretty well. However I am not sure it is written properly. I wonder is there any way to make it more elegant. Any advices on code refactoring are appriciated.
class Program
{
static void Main(string[] args)
{
//some time consuming job simulation
Action routine = () =>
{
for (int i = 0; i <= 15; i++)
{
Thread.Sleep(700);
}
};
Program program = new();
program.AwaitRoutine(routine);
Console.ReadKey();
}
public void AwaitRoutine(Action function, string screenFlag = "Processing")
{
Task task = new Task(function);
Console.CursorVisible = false;
bool isrunning = true;
task.Start();
Console.Write(screenFlag);
while (isrunning)
{
for (int i = 0; i <= 2; i++)
{
Thread.Sleep(500);
Console.Write(".");
if (task.IsCompleted) { isrunning = false; break; }
}
Thread.Sleep(500);
Console.CursorLeft = screenFlag.Length;
Console.Write(" ");
Console.CursorLeft = screenFlag.Length;
}
task.Wait();
Console.CursorLeft = 0;
Console.Clear();
Console.WriteLine("Done");
Console.CursorVisible = true;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
