Click here to Skip to main content
15,888,148 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to update Geocode information in database which I am doing via calling Google MAPs API. To speedup the process I would like to use Parallel.ForEach on database query and then add the results to list of objects which I have done. I have two questions.

1. Is it OK to call Parallel.ForEach on database select query ?
2. Adding values to result list require locking it ?

My code is as below :

C#
string key = ConfigurationManager.AppSettings["APIKey"];
int batchSize = int.Parse(ConfigurationManager.AppSettings["BatchSize"].Trim());
Object lockMe = new Object(); 

PROD_Transform_MovexEntities objEntities = new PROD_Transform_MovexEntities();

var selected = (from cus in objEntities.OCUSAD_LongLat
				where !cus.OPCUA1.StartsWith("PICK UP")
				&& !cus.OPCUA2.StartsWith("PO BOX")
				&& cus.Cust_Long == null
				&& cus.Match_Date == null
				select cus).Take(batchSize);

List<CustomerAddress> lstResult = new List<CustomerAddress>(batchSize);

//Is this OK ?
Parallel.ForEach(selected, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, sel => {
	CustomerAddress objThisCus = new CustomerAddress();
	objThisCus.CustomerNumber = sel.OPCUNO;
	objThisCus.AddressRT = sel.OPADRT;
	objThisCus.AddressID = sel.OPADID;

	try
	{
		string address = sel.OPCUA2 + " " + sel.OPCUA3 + " " + sel.OPCUA4;
		GeoDetail objResult = GetGeoDetails(key, address); // Get Geocodes from Google MAPs API call
		objThisCus.Latitude = objResult.Latitude;
		objThisCus.Longitude = objResult.Longitude;
		objThisCus.AddressType = objResult.AddressType;
		
		if(objResult.Error.ToUpper()!="OVER_QUERY_LIMIT")
		{
			lock (lockMe) 
			{
				lstResult.Add(objThisCus);
			}
		}

	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.ToString());
	}

});
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900