.NET 4.5 Task Based Console Application with Progress

Lets say you need to create a simple .NET 4.5 application for processing some data… The quickest way to do that is to create a new Console Application in Microsoft Visual Studio 2012. I’m assuming that you already know how to do all of that… If not, you can Google it!

Once you have that, the first thing we will do is start out with your work process, this will be the actual Task that does all of the processing. We’re going to use the Task in the most basic fashion, so if you need to do more with it, take a look at System.Threading.Task on MSDN.

Here is the initial code to get you started; a basic entry point that calls a task and then waits for it to complete.

static Task DoWorkAsync()
{
	return Task.Factory.StartNew(() => {
			//Do Some Work...
			Thread.Sleep(250);
		}
	});
}
static void Main(string[] args)
{
	// Start the Task
	Task t = DoWorkAsync();

	// Wait for the task to complete
	t.Wait();
}

With that code, you will get a simple application that will spin off a new thread that will run the code in the DoWorkAsync function. We call t.Wait() in the main thread so that the application doesn’t terminate before the task completes.

That is all it basically takes to write a simple Task based console application in .NET 4.5. But just for the sake of fun, lets add some more detailed processing and some way of reporting back some level of progress.

public static int spinnerPos = 0;
public delegate void UpdateProgressDelegate(float pctComplete);
public static UpdateProgressDelegate UpdateProgress = (float pctComplete) => {
	if (pctComplete >= 100f) {
		Console.Write("\rProcess Complete!".PadRight(Console.BufferWidth));
	}
	else {
		char[] spinner = new char[] { '-', '\\', '|', '/' };
		Console.Write(string.Format("\rWorking... {0} - {1:0.0}%", spinner[spinnerPos], pctComplete).PadRight(Console.BufferWidth));
		spinnerPos = (spinnerPos >= 3) ? 0 : spinnerPos + 1;
	}
};

static Task DoWorkAsync()
{
	return Task.Factory.StartNew(() => {

		// Show the starting progress
		UpdateProgress(0f);

		int loopCount = 15;
		for (int i = 0; i < loopCount; i++) {

			Thread.Sleep(250);

			// Update the progress
			float pctComplete = (((float)(i + 1) / (float)loopCount) * 100f);
			UpdateProgress(pctComplete);
		}
	});
}

static void Main(string[] args)
{
	// Start the Task
	Task t = DoWorkAsync();

	// Wait for the task to complete
	t.Wait();

	Console.Write("\r\n\r\nDone!");
	Console.ReadLine();
}

With these updates the application will report back some basic progress to the console using a simple delegate.

Take the code and play around with it; it’s a good base for any long running process in a console application.

Leave a Reply

Your email address will not be published. Required fields are marked *