I have a DB table with 7 columns and 10rows. Each row is provided an input parameter to a web api call, and the response returned by the api, is inserted into a table. My problem is, the Parallel.Foreach
is not producing the same result as the regular ForEach.
Specifically, if 1st row has address as "123 Jump Street Arizona Us", I get a response from web api with the standardized address as "123 Jump Street Arizona USA", like that I have 10 different rows with 10 different input address. However, the output response I get from Parallel.Foreach
is for the same address repeated 5 times. And the next time i run it, it is a different result altogether
Could someone please point out why this is happening and the potential solution?
Here is my code:
public void Main()
{
// TODO: Add your code here
string query = "SELECT ADDR_LINE_ONE,ADDR_LINE_TWO,ADDR_LINE_THREE,COUNTRY,PROVINCE,CITY_NAME,POSTAL_CODE FROM Addresstestpoc";
try
{
using (OleDbConnection connection = new OleDbConnection(conn))
{
OleDbCommand command = new OleDbCommand(query, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
int i = reader.FieldCount;
bool b = reader.HasRows;
Parallel.ForEach(GetFromReader(reader), record =>
{
//AddrOne = record[0].ToString();
string AddrOne = record.GetString(0);
string AddrTwo = record.GetString(1);
string AddrThree = record.GetString(2);
string Country = record.GetString(3);
string Province = record.GetString(4);
string City = record.GetString(5);
string PostalCode = record.GetString(6);
string Sender = "G";
//sqlk = (string)Dts.Variables["User::sqlconn"].Value;
standardizeAddressReturn result;
string data = string.Empty;
string queri;
MDMStandardizeAddressService web = new MDMStandardizeAddressService();
try
{
result = web.standardizeAddress(AddrOne, AddrTwo, AddrThree, City, Province, PostalCode, Country, Sender);
data = SerializeToXml(result);
queri = "insert into [CPM].[dbo].[AddressResponsetest_new] values ('" + data + "')";
//MessageBox.Show(data);
insertintosql(queri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
});
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
IEnumerable<IDataRecord> GetFromReader(IDataReader reader)
{
while (reader.Read()) yield return reader;
}