C# Multi Threaded Application

Updated 23/03/2021

Task List

Running Tasks in parallel is very simple, the collection of tasks below return a string and its workload is simply to create a text file and then delay for x milliseconds to mimic a longer workload.

The complete code for these snippets is at https://github.com/carlpaton/ThreadingDemo/tree/main/src/RunTasksInParallel

Some configuration

1
2
var millisecondsTimeout = 2000;
var taskCount = 10;

Create the service that does some work and has the mimic of a longer workload.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public async Task<string> HandleAsync(int millisecondsTimeout) 
{
var dateTime = DateTime.Now;
var fileName = $"{dateTime.Hour}_{dateTime.Minute}_{dateTime.Second}_{dateTime.Millisecond}.txt";
Console.WriteLine("{0} : {1}", dateTime, fileName);

var sb = new StringBuilder();
sb.Append($"{dateTime} {fileName}");

await File.WriteAllTextAsync($"data/{fileName}", sb.ToString());

await Task.Delay(millisecondsTimeout);
return fileName.ToString();
}

Create the task list and populate it with the workload.

Note that adding them to the list is not what starts the tasks, its the File.WriteAllTextAsync that would have been the trigger.

1
2
3
4
5
6
var tasks = new List<Task<string>>();

for (int i = 0; i < taskCount; i++)
{
tasks.Add(createFileService.HandleAsync(millisecondsTimeout));
}

Then wait for the tasks to all complete

1
await Task.WhenAll(tasks);

Task Array

This was adapted from stackoverflow.com examples and is very simliar to the list example above however the tasks are started using Task.Factory.StartNew.

1
2
3
4
5
6
7
8
9
10
var listOfSomething = new PopulateListOfSomething();
var tasks = new Task[listOfSomething.Count];

for (int i = 0; i < listOfSomething.Count; i++)
{
var someService = new SomeService(listOfSomething[i]);
tasks[i] = Task.Factory.StartNew(() => someService.Go());
}

Task.WaitAll(tasks);

References