I have a method that need to call webservice to get data. If each record(total 200) needs to be called once webservice,then it will take a long time(per more than 10 seconds one response). So I use asynchronous to improve efficiency. But I meet a problem. When using the Task, it should call 200 times Webservice, but it only calls more than 100 times lead to incomplete result.
Hope someone can help me, thank you very much.
Code:
string EffectiveDate = string.Empty;
IList<Task<string>> list = new List<Task<string>>();
foreach (DataRow dr in rows)
{
var task = Task.Factory.StartNew(new Func<string>(() =>
{
string result = string.Empty;
string columnId;
try
{
var rates = GetMainRateModel(dr);
lock (_objMainRatesAsync)
{
long seq = _redis.Core.IncrementValue(_currUserKey);
columnId = dr["ColumnId"].GetString();
EffectiveDate = Convert.ToDateTime(dr["Validity date"]).ToString("yyyy-MM-dd");
if (rates != null)
{
foreach (var rate in rates)
{
var surCharges = GetContractSurchargeModel(rate, EffectiveDate);
rate.Surcharges = surCharges;
GetVATOSSurcharges(rate, surCharges, EffectiveDate, dr);
}
_redis.Hash_Set(_currRates, columnId, rates);
}
}
}
catch (Exception eex)
{
lock (_objProcessRateAsync)
{
_sbErrors.AppendLine(string.Format("Error, when the get data from web service. Detail message: {0}", eex.Message));
}
result = eex.Message;
}
return result;
}));
list.Add(task);
}
Task.WaitAll(list.ToArray());