C# .NET: Multi-Threaded Programming Using Tasks in .NET

12/23/2013 5:13:27 PM

The following is used to process a list of objects in a multi-threaded fasion using threads.

There are 2 examples. The second uses a shared list of results. It uses the System.Collections.Concurrent.ConcurrentBag for thread-safe sharing of the results.

public static void Start_Here_01(List<MyObject> myObjects)
{
	//create an empty list to hold tasks
	var tasks = new List<Task>();

	//loop through the object list
	foreach (MyObject myObject in myObjects)
	{		
		//for any values that are specific to the current task contenxt, the variable/object must be created within the loop
		DateTime now = DateTime.Now;
		
		var task = Task.Factory.StartNew(() => Process_Things_Async(myObject, now));
		tasks.Add(task);
	}

	//wait till all tasks are done
	Task.WaitAll(tasks.ToArray());
}


public static void Process_Things_Async(MyObject myObject, DateTime now)
{
	//Do something	
}

/////////////////////////////////////////////////////////

public static void Start_Here_02(List<MyObject> myObjects)
{
	//list to hold results
	System.Collections.Concurrent.ConcurrentBag<MyResults> myResults = new System.Collections.Concurrent.ConcurrentBag<MyResults>();
	
	//create an empty list to hold tasks
	var tasks = new List<Task>();

	//loop through the object list
	foreach (MyObject myObject in myObjects)
	{		
		//for any values that are specific to the current task contenxt, the variable/object must be created within the loop
		DateTime now = DateTime.Now;
		
		var task = Task.Factory.StartNew(() => Process_Things_Async(myObject, now, ref myResults));
		tasks.Add(task);
	}

	//wait till all tasks are done
	Task.WaitAll(tasks.ToArray());
	
	//do something with the results
}



public static void Process_Things_Async(MyObject myObject, DateTime now, ref System.Collections.Concurrent.ConcurrentBag<MyResults> myResults)
{
	//Do something
	
	//add results to the shared myResults list
}