I am trying to convert a synchronous method with GetAwaiter()GetResult() to an asynchronous method. I have the following code:
private List<MyObject> GetPairsToHandle(SpecificationBuilder specificationBuilder)
{
using (var context = _contextFactory.Create())
{
var toHandleFromDb = GetItemsToHandle().ToList();
var leadsSet = new Dictionary<int, ProcessingLead>();
var toHandle = toHandleFromDb
.Select(o =>
{
ProcessingLead lead = null;
if (o.Item1 != null)
{
if (leadsSet.ContainsKey(o.Item1.ID))
lead = leadsSet[o.Item1.ID];
else
{
lead = _entityMapper.Map(o.Item1);
leadsSet.Add(o.Item1.ID, lead);
}
}
ProcessingLeadConsumer consumer = null;
if (o.Item2 != null)
{
if (lead == null)
{
consumer = new ProcessingLeadConsumer
{
Id = o.Item2.Id,
CompanyGuid = o.Item2.CompanyGuid
};
}
else
{
consumer = _companyServiceFactory.Create(lead.Country, lead.Brand).GetCompanyAsync(o.Item2.CompanyGuid).GetAwaiter().GetResult();
}
}
return new MyObject(lead, consumer);
})
.ToList();
return toHandle;
}
}
Instead of .GetAwaiter().GetResult()
I would want it to run asynchronously. So I changed it to the following:
var toHandle = toHandleFromDb
.Select(async o =>
{
ProcessingLead lead = null;
if (o.Item1 != null)
{
if (leadsSet.ContainsKey(o.Item1.ID))
lead = leadsSet[o.Item1.ID];
else
{
lead = _entityMapper.Map(o.Item1);
leadsSet.Add(o.Item1.ID, lead);
}
}
ProcessingLeadConsumer consumer = null;
if (o.Item2 != null)
{
if (lead == null)
{
consumer = new ProcessingLeadConsumer
{
Id = o.Item2.Id,
CompanyGuid = o.Item2.CompanyGuid
};
}
else
{
consumer = await _companyServiceFactory.Create(lead.Country, lead.Brand).GetCompanyAsync(o.Item2.CompanyGuid);
}
}
return new MyObject(lead, consumer);
})
.ToList();
Now I have to questions:
- How do I convert
List<System.Threading.Tasks.Task..
to<List<MyObject
- Is it safe to call an async lamda from a synchronous method? I cannot convert this method to async. What would be the best solution?