C# Parallel.ForEach approach

I have a process that uses DataTables to hold rows of data and at the end of the process it uses SQLBulkCopy to write the resulting data to the database. If I wanted to use Parallel.ForEach around the loop of Customers being processed I will have to use Locks on the DataTable / DataRow's as its not thread safe. All I really need is a container to hold the results and then the ability to write this data to SQL at the end. Would it be advisable to use a ConcurrentBag collection to hold the data as its threadsafe and then at the end of the process (outside of the Parallel.ForEach) convert the ConcurrentBag of objects containing the data into a DataTable and then use SQLBulkCopy to write the data?

Something like:

ConcurrentBag<Data1> Data1 = new ConcurrentBag<Data1>();
ConcurrentBag<Data2> Data2 = new ConcurrentBag<Data2>();

Parallel.Foreach(Customer, cust=>
{
    // Do stuff for Data1
    Data1.Add(obj);

   // Do stuff for Data2
   Data2.Add(obj);
}

foreach (obj in Data1)
{
    // Convert to DataRow and add to DataTable  
}

SQLBulkCopy DataTable to SQL.
LVL 2
Mr KnackeredAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
I would take it a step further.

You could build your datatable(s) as you consume your object(s); e.g. -
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace EE_Q28763719
{
	class Program
	{
		static BlockingCollection<DataRow> productRows = new BlockingCollection<DataRow>();
		static BlockingCollection<DataRow> personRows = new BlockingCollection<DataRow>();

		static DataTable products = Extensions.CreateTable<Product>();
		static DataTable people = Extensions.CreateTable<Person>();

		static void Main(string[] args)
		{
			Task.Factory.StartNew(() =>
				{
					Console.WriteLine("Producer has started...");
					Parallel.ForEach((from i in Enumerable.Range(0, 10000) select i), i =>
						{
							productRows.Add(new Product() { ID = i, Name = string.Format("Product{0}", i), Price = i + 5 * 2 }.AsDataRow());
							personRows.Add(new Person() {ID = i, Name = string.Format("Person{0}", i)}.AsDataRow());
							Console.Write(".");
						});
					productRows.CompleteAdding();
					personRows.CompleteAdding();
				}, TaskCreationOptions.LongRunning);

			Task.Factory.StartNew(() =>
				{
					Console.WriteLine("Consumer has started...");
					foreach (DataRow row in productRows.GetConsumingEnumerable())
						products.Rows.Add(row.ItemArray);

					foreach (DataRow row in personRows.GetConsumingEnumerable())
						people.Rows.Add(row.ItemArray);
				}, TaskCreationOptions.LongRunning).ContinueWith(t => 
				{
					Console.WriteLine("Finished creating the data tables.");
					Console.WriteLine("Press any key to exit...");
				});
			Console.ReadKey();
		}
	}

	class Product
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public decimal Price { get; set; }
	}

	class Person
	{
		public int ID { get; set; }
		public string Name { get; set; }
	}

	static class Extensions
	{
		public static DataRow AsDataRow<T>(this T instance)
		{
			Type entity = typeof(T);
			DataRow row = CreateTable<T>().NewRow();
			PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entity);
			foreach (PropertyDescriptor property in properties)
				row[property.Name] = property.GetValue(instance);
			return row;
		}

		public static DataTable CreateTable<T>()
		{
			Type entity = typeof(T);
			DataTable table = new DataTable(entity.Name);
			PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entity);
			foreach (PropertyDescriptor property in properties)
			{
				if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
					table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
				else
					table.Columns.Add(property.Name, property.PropertyType);

			}
			return table;
		}
	}
}

Open in new window

-saige-
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.