Aspnet core Parallels operation DbContext problem - c#

I've a problem when I use Pararrel function in aspnetcore, in particular when in the cycle i try to save something in database. I get my data from externarl api and deseserialize it in my class.
This is the Parallel code.
Root players = JsonConvert.DeserializeObject<Root>(responseStream);
var bulkhead = Policy.BulkheadAsync(10, Int32.MaxValue);
var tasks = new List<Task>();
foreach (var player in players.players)
{
var t = bulkhead.ExecuteAsync(async () =>
{
int wyId = Convert.ToInt32(player.wyId);
HttpRequestMessage secondRequest = createRequest("https://apirest.com/v2/players/" + wyId + "?details=currentTeam&imageDataURL=true");
var client2 = _clientFactory.CreateClient();
var response2 = await client2.SendAsync(secondRequest);
if (response2.IsSuccessStatusCode)
{
var responseStream2 = await response2.Content.ReadAsStringAsync();
dynamic playerFullDetails = JsonConvert.DeserializeObject<dynamic>(responseStream2);
int wyId2 = Convert.ToInt32(playerFullDetails.wyId);
int marketValue = 0;
HttpRequestMessage tirthRequest = createRequest("https://apirest.com/v2/players/" + wyId2 + "/marketvalue");
var client3 = _clientFactory.CreateClient();
var response3 = await client3.SendAsync(tirthRequest);
if (response3.IsSuccessStatusCode)
{
var responseStream3 = await response3.Content.ReadAsStringAsync();
dynamic marketValueResponse = JsonConvert.DeserializeObject<dynamic>(responseStream3);
if (marketValueResponse.marketValue != 0)
{
marketValue = Convert.ToInt32(marketValueResponse.marketValue);
}
}
DateTime birthday = Convert.ToDateTime(playerFullDetails.birthDate);
int age = DateTime.Now.Year - birthday.Year;
Player finalPlayer = new Player();
finalPlayer.PlayerId = wyId2;
finalPlayer.MarketValue = marketValue;
finalPlayer.Value = Convert.ToDouble(marketValue) / Convert.ToDouble(1000000);
finalPlayer.Firstname = playerFullDetails.firstName;
finalPlayer.Lastname = playerFullDetails.lastName;
finalPlayer.Name = playerFullDetails.shortName;
finalPlayer.Position = playerFullDetails.role.name;
finalPlayer.Height = playerFullDetails.height;
finalPlayer.Foot = playerFullDetails.foot;
finalPlayer.IsLocked = false;
finalPlayer.Team = playerFullDetails.currentTeam != null ? playerFullDetails.currentTeam.name : "";
finalPlayer.TeamId = playerFullDetails.currentTeam != null ? playerFullDetails.currentTeam.wyId : 0;
finalPlayer.CompetitionId = 524;
finalPlayer.UpdatedDay = DateTime.Now;
finalPlayer.League = "Serie A";
finalPlayer.Age = age;
Player playerExist = await _context.Player.Where(x => x.PlayerId == wyId2).SingleOrDefaultAsync();
if (playerExist == null)
{
if (finalPlayer.TeamId != 0)
{
await _context.Player.AddAsync(finalPlayer);
await _context.SaveChangesAsync();
}
}
if (finalPlayer.TeamId != 0)
{
Team teamExist = await _context.Team.Where(x => x.TeamId == finalPlayer.TeamId).SingleOrDefaultAsync();
if (teamExist == null)
{
Team team = new Team();
team.TeamId = finalPlayer.TeamId;
team.TeamName = finalPlayer.Team;
await _context.Team.AddAsync(team);
await _context.SaveChangesAsync();
}
}
}
});
tasks.Add(t);
}
await Task.WhenAll(tasks);
The function isert 50/60 (in total would be 500) element in db and finally i receive this error
A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
Thanks

It's best practice to use 1 dbcontext per unit of work, and the dbcontext is not thread safe
So either create a new dbcontext per thread or lock access with someting like a semaphore otherwise you will always get unstable code

Related

AsyncEnumerator library not processing collection

I am using the AsyncEnumerator library by #Serge Semenov, and after getting the orders, creating the ConcurrentBag and setting count to 0, nothing happens - can anyone see what's missing here? It never hits the processedOrders.ToList() line when debugging.
private async Task<List<OrderDto>> ProcessOrderEvents(DateTime cob)
{
var orders = await _client.GetOrderEvents(cob);
var processedOrders = new ConcurrentBag<OrderDto>();
var count = 0;
await orders.ParallelForEachAsync(async order =>
{
var orderDto = new FidessaOrderDto {Cob = cob};
var orderId = order.Ids.PrimaryId;
Debug.WriteLine($"Processing OrderId: {orderId} #= {++count}");
var instrumentDetails = await GetInstrumentDetails(order);
if (instrumentDetails.Results.Any())
{
//...
}
var tradeDetails = await _client.GetTrade(tradeId: fill, cob);
processedOrders.Add(orderDto);
}, maxDegreeOfParallelism:2);
return processedOrders.ToList();
}
Update: Adding Test root.
[TestMethod]
public async Task Test_20_07_2022()
{
var service = new DataService(new ApiClient());
var data = await service.ProcessData(new DateTime(2022, 07, 20), ReportDataType.Orders);
Assert.AreEqual(920, data.Count);
}
public async Task<List<OrderDto>> ProcessData(DateTime cob,
ReportDataType dataType)
{
await PopulateRouteEvents(cob);
var reportData = new List<OrderDto>();
if (dataType == ReportDataType.Orders)
reportData = await ProcessOrderEventsTpl(cob);
return reportData;
}

Running a thread in the background when controller return to UI with full results - async call of a function from Controller method

Hi I have Controller method as below
[HttpPost]
public JsonResult Post(string vehiclesString, string Entity, int EntityId, ApplicationUser CurrentUser)
{
//https://stackify.com/understanding-asp-net-performance-for-reading-incoming-data/
List<Vehicle> vehicles = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Vehicle>>(vehiclesString);
InputFieldController c = new InputFieldController();
var errors = new List<string>();
try
{
//let's get model for each of the input field
InputFieldController icController = new InputFieldController();
List<InputField> fields = icController.GetNamesValues("VehicleField", -1, "Vehicle", 0);
foreach (Vehicle vehicle in vehicles)
{
//convert array of strings into array of input fields
if (fields.Count != vehicle.ValueStrings.Count)
{
throw new Exception("Vehicle columns mismatch. Expected "
+ fields.Count + " fields, but received " + vehicle.ValueStrings.Count);
}
for (int i = 0; i < fields.Count; i++)
{
InputField field = fields[i];
string cell = vehicle.ValueStrings[i];
if ((cell != null || cell != String.Empty) && (field.Type == "radio" || field.Type == "dropdown"))
{
var f = field.InputDropdowns.Where(x => x.Name == cell).FirstOrDefault();
if (f != null)
{
field.InputValue.InputDropdownId = f.InputDropdownId;
}
else
field.InputValue.InputDropdownId = null;
}
else
{
field.InputValue.Value = cell;
}
vehicle.Values.Add(field);
}
vehicle.Blob = Newtonsoft.Json.JsonConvert.SerializeObject(vehicle.Values);
Vehicle v = new Vehicle();
if (vehicle.VehicleId == 0)
{
v = this.DomainLogicUnitOfWork.VehicleManager.Create(vehicle, Entity, EntityId);
}
}
JsonResult data = Json(new
{
success = true,
});
List<Vehicle> vehiclesList = this.DomainLogicUnitOfWork.VehicleManager.List(Entity, EntityId);
if (vehiclesList != null)
foreach (Vehicle v in vehiclesList)
{
if ((v != null) && (v.Blob != null))
v.Values = Newtonsoft.Json.JsonConvert.DeserializeObject<List<InputField>>(v.Blob);
}
//Task task = Task.Run(async () => await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(Entity, EntityId));
/*
* Here I have to call the this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(string Entity, int EntityId) asynchronously
* but return the data without waiting for the CreateOrUpdate to complete
*/
System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(vehiclesList, Entity, EntityId);
});
return data;
}
catch (Exception ex)
{
LogHandler.LogError(9000, "Error updating input fields", ex);
errors.Add("Error 9000:" + ex.Message);
return Json(new
{
error = ex.Message
});
}
}
And I have CreateOrUpdate method defined as below in VehicleInfoManager class
public async Task CreateOrUpdate(string Entity, int EntityId)
{
//do some stuff
var task = Task.Run(() => Test(Entity, EntityId));
//do other stuff
await task;
//some more stuff
}
And Test method is as follows
private void Test(string Entity, int EntityId)
{
List<VehicleInfo> addList; List<VehicleInfo> updateList;
try
{
this.GetAddAndUpdateList(Entity, EntityId, out addList, out updateList);
if ((addList != null) && (addList.Count > 0))
using (var cont = this.UnitOfWork.Context)
{
foreach (var a in addList)
{
cont.VehicleInfos.Add(a);
}
cont.SaveChanges();
}
if ((updateList != null) && (updateList.Count > 0))
using (var cont = this.UnitOfWork.Context)
{
foreach (var a in updateList)
{
var aa = cont.VehicleInfos?.Where(x => x.VehicleInfoId == a.VehicleInfoId)?.FirstOrDefault();
aa.Address_City = a.Address_City;
aa.Address_Country = a.Address_Country;
aa.Address_StateCode = a.Address_StateCode;
aa.Address_Street1 = a.Address_Street1;
aa.Address_Street2 = a.Address_Street2;
aa.Address_Zip = a.Address_Zip;
aa.ChassisYear = a.ChassisYear;
aa.EngineFamilyName = a.EngineFamilyName;
aa.Entity = a.Entity;
aa.EntityId = a.EntityId;
aa.InputFieldEntity = a.InputFieldEntity;
aa.InputFieldEntityId = a.InputFieldEntityId;
aa.InputFieldGroup = a.InputFieldGroup;
aa.LicensePlate = a.LicensePlate;
aa.Manufacturer = a.Manufacturer;
aa.ModelYear = a.ModelYear;
aa.PurchasedDate = a.PurchasedDate;
aa.RegHoldClearBy = a.RegHoldClearBy;
aa.RegHoldClearDate = a.RegHoldClearDate;
aa.RegHoldComment = a.RegHoldComment;
aa.RegHoldSet = a.RegHoldSet;
aa.RegHoldSetBy = a.RegHoldSetBy;
aa.RegHoldSetDate = a.RegHoldSetDate;
aa.TrailerPlate = a.TrailerPlate;
aa.UpdatedBy = a.UpdatedBy;
aa.UpdatedDate = a.UpdatedDate;
aa.VehicleId = a.VehicleId;
aa.VehicleOperator = a.VehicleOperator;
aa.VehicleOwner = a.VehicleOwner;
aa.VIN = a.VIN;
}
cont.SaveChanges();
}
}
catch (Exception ex)
{
ARB.Logging.LogHandler.LogError(9001, "CreateOrUpdate(string Entity, int EntityId) in class VehicleInfoManager", ex);
throw ex;
}
}
What I want is, I want two things here
the Post method to call or start the CreateOrUpdate method as background call but instead of waiting until the CreateOrUpdate method finishes, it should return the result data to UI and continue the big task CreateOrUpdate in the background.
Is there anyway to start the background method CreateOrUpdate after sometime like (10 mins etc) post method returns to UI, if it can't be done, its OK we don't have to worry but just asking if there is anyway to trigger this from within the same application
When I implemented it in the above way, even after using System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem I am still getting the null http context at the following location
user = System.Web.HttpContext.Current.User.Identity.Name; url = System.Web.HttpContext.Current.Request.Url.ToString();
System.Web.HttpContext.Current is coming out as null.
and the application is breaking,
I chaned my async call to the following to use HostingEnvironment.QueueBackgroundWorkItem, still the same htt current context is coming out as null, any help please
System.Web.Hosting.HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
await this.DomainLogicUnitOfWork.VehicleInfoManager.CreateOrUpdate(Entity, EntityId);
});
Thank you
System.Web.HttpContext.Current is maintained by the ASP.NET's SynchronizationContext.
When you start a new Task, the code will be executing on another thread pool thread without a SynchronizationContext and the value of System.Web.HttpContext.Current is not safe to use, whatever its value.
When the execution of the action method (Post) ends, the request will end and the HttpContext instance will be invalid, even if you mange to get a reference to it.
Also, there is no guarantee that that code you posted to the thread pool will run to complete, since it's out of ASP.NET control and ASP.NET won't be aware of it if IIS decides, for some reason, to recycle the application pool or the web application.
If you to post background work, use HostingEnvironment.QueueBackgroundWorkItem. Beware if its constraints.

Creating new Task is not running the entire method

I have a calculation that does I/O I want to send to another thread so on the web site the user can goto the next page without waiting for the calculation to finish. From what I understand are I need to do is call the method like this
var backgroundTask = Task.Run(() => CalculateSet(uow, profile, userId, specialtyCode ));
But when I do this is seems to call one line in the method and goes away.. non of the work is done.
Am I missing something ?
[Fact]
public void Calculation_Xls()
{
string currentDirectory = Directory.GetCurrentDirectory();
string filesDirectory = currentDirectory + "\\Files";
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
Configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
int i = 0; //outer loop
UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder.Options));
using (var stream = System.IO.File.Open(filesDirectory + "\\t2UserProfileDataTwoUserPerSpecialty.xlsx",
FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
do
{
while (reader.Read())
{
if (i != 0)
{
var userId = reader.GetString(0);
var specialtyCode = reader.GetString(1);
var userProfileElement1_WorkExp = reader.GetValue(2);
var userProfileElement2_VolExp = reader.GetValue(3);
var userProfileElement3_ResExp = reader.GetValue(4);
var userProfileElement4_Pubs = reader.GetValue(5);
var userProfileElement5_AOA = reader.GetValue(6);
var userProfileElement6_Nspecialties = reader.GetValue(7);
var userProfileElement7_PercentApps = reader.GetValue(8);
//Create profile
UserProfileData profile = new UserProfileData();
profile.UserProfileElement1_WorkExp = Convert.ToInt32(userProfileElement1_WorkExp);
profile.UserProfileElement2_VolExp = Convert.ToInt32(userProfileElement2_VolExp);
profile.UserProfileElement3_ResExp = Convert.ToInt32(userProfileElement3_ResExp);
profile.UserProfileElement4_Pubs = Convert.ToInt32(userProfileElement4_Pubs);
profile.UserProfileElement5_Aoa = Convert.ToBoolean(userProfileElement5_AOA);
profile.UserProfileElement6_Nspecialties = Convert.ToInt32(userProfileElement6_Nspecialties);
profile.UserProfileElement7_PercentApps = Convert.ToInt32(userProfileElement7_PercentApps);
//Calculate for set of programs. Selects one row at a time from XLS. BulkInsert into DB
//THIS ONLY RUNS ONE LINE OF THE METHOD
var backgroundTask = Task.Run(() => CalculateSet(uow, profile, userId, specialtyCode ));
//THIS WORKS
//CalculateSet(uow, profile, userId, specialtyCode);
}
i++;
Debug.WriteLine("Bulkcreate complete " + i);
//only process xxx rows
if (i > 1)
{
break;
}
}
} while (reader.NextResult());
}
}
Debug.WriteLine("Should get here quickly and not wait until task is done");
}
private void CalculateSet(UnitOfWork uow, UserProfileData profile, string userId, string specialtyCode)
{
//I CAN HIT THIS BREAKPOINT!
//get specialtyId from code
var specialtyId = uow.RefMedicalSpecialtyRepository
.Find(x => x.Code == specialtyCode).FirstOrDefault().Id;
//NEVER GET TO THIS BREAKPOINT
//loop through all programs for speciality
var programsForSpecialty = uow.RefProgramDetailDataRepository
.Find(x => x.RefMedicalSpecialtyId == specialtyId);
//List for bulk insert
// List<UserProgram> userPrograms = new List<UserProgram>();
//Write a row for each program
foreach (RefProgramDetailData rpdd in programsForSpecialty.ToList())
{
//Get program info
var programProfile = LoadData.Load_RefProgramProfileData(rpdd.Code);
//Calculate results
var userProgram = _calculator.CalculateAll(programProfile, profile, specialtyId, userId);
//If the Program can not be found in program detail then skip insert
if (userProgram == null)
{
Debug.WriteLine("Program NULL");
}
else
{
//Write results to UserProgram
uow.UserProgramRepository.Create(userProgram);
//userPrograms.Add(userProgram);
Debug.WriteLine("Program " + programProfile.ProgramCode);
}
}
//bulk insert
// uow.UserProgramRepository.BulkCreate(userPrograms);
}
}
EDIT 1: I put this in my controller. But it is waiting for the Task to finish before it redirects. Why isn't it redirecting immediately ?
await Task.Run(() => _calculator.CalculateAllSet(_unitOfWork, userProfileData, msId, null));
return RedirectToAction("Index", "Home");
Can you try like that.
[Fact]
public async Task Calculation_Xls()
{
string currentDirectory = Directory.GetCurrentDirectory();
string filesDirectory = currentDirectory + "\\Files";
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
Configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
int i = 0; //outer loop
UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder.Options));
using (var stream = System.IO.File.Open(filesDirectory + "\\t2UserProfileDataTwoUserPerSpecialty.xlsx",
FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
do
{
while (reader.Read())
{
if (i != 0)
{
var userId = reader.GetString(0);
var specialtyCode = reader.GetString(1);
var userProfileElement1_WorkExp = reader.GetValue(2);
var userProfileElement2_VolExp = reader.GetValue(3);
var userProfileElement3_ResExp = reader.GetValue(4);
var userProfileElement4_Pubs = reader.GetValue(5);
var userProfileElement5_AOA = reader.GetValue(6);
var userProfileElement6_Nspecialties = reader.GetValue(7);
var userProfileElement7_PercentApps = reader.GetValue(8);
//Create profile
UserProfileData profile = new UserProfileData();
profile.UserProfileElement1_WorkExp = Convert.ToInt32(userProfileElement1_WorkExp);
profile.UserProfileElement2_VolExp = Convert.ToInt32(userProfileElement2_VolExp);
profile.UserProfileElement3_ResExp = Convert.ToInt32(userProfileElement3_ResExp);
profile.UserProfileElement4_Pubs = Convert.ToInt32(userProfileElement4_Pubs);
profile.UserProfileElement5_Aoa = Convert.ToBoolean(userProfileElement5_AOA);
profile.UserProfileElement6_Nspecialties = Convert.ToInt32(userProfileElement6_Nspecialties);
profile.UserProfileElement7_PercentApps = Convert.ToInt32(userProfileElement7_PercentApps);
//Calculate for set of programs. Selects one row at a time from XLS. BulkInsert into DB
//THIS ONLY RUNS ONE LINE OF THE METHOD
var backgroundTask = await Task.Run(() => CalculateSet(uow, profile, userId, specialtyCode ));
//THIS WORKS
//CalculateSet(uow, profile, userId, specialtyCode);
}
i++;
Debug.WriteLine("Bulkcreate complete " + i);
//only process xxx rows
if (i > 1)
{
break;
}
}
} while (reader.NextResult());
}
}
Debug.WriteLine("Should get here quickly and not wait until task is done");
}
private void CalculateSet(UnitOfWork uow, UserProfileData profile, string userId, string specialtyCode)
{
//I CAN HIT THIS BREAKPOINT!
//get specialtyId from code
var specialtyId = uow.RefMedicalSpecialtyRepository
.Find(x => x.Code == specialtyCode).FirstOrDefault().Id;
//NEVER GET TO THIS BREAKPOINT
//loop through all programs for speciality
var programsForSpecialty = uow.RefProgramDetailDataRepository
.Find(x => x.RefMedicalSpecialtyId == specialtyId);
//List for bulk insert
// List<UserProgram> userPrograms = new List<UserProgram>();
//Write a row for each program
foreach (RefProgramDetailData rpdd in programsForSpecialty.ToList())
{
//Get program info
var programProfile = LoadData.Load_RefProgramProfileData(rpdd.Code);
//Calculate results
var userProgram = _calculator.CalculateAll(programProfile, profile, specialtyId, userId);
//If the Program can not be found in program detail then skip insert
if (userProgram == null)
{
Debug.WriteLine("Program NULL");
}
else
{
//Write results to UserProgram
uow.UserProgramRepository.Create(userProgram);
//userPrograms.Add(userProgram);
Debug.WriteLine("Program " + programProfile.ProgramCode);
}
}
//bulk insert
// uow.UserProgramRepository.BulkCreate(userPrograms);
}
}

using data on the view from async method

I'm using the geolocator plugin to retrieve my current location and add a pin to the page. Here is the service for this:
tasks.cs
public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation()
{
try
{
var locator = Plugin.Geolocator.CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1));
if (position != null)
{
return position;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to get location, may need to increase timeout: " + ex);
}
return new Plugin.Geolocator.Abstractions.Position();
}
I'm trying to use it in the view like this :
public MapPage(List<Models.xxx> xxx, Models.yyy yyy )
{
InitializeComponent();
Tasks ts = new Tasks();
var myLocation = ts.GetDeviceCurrentLocation();
var latitudeIm = myLocation.Result.Latitude;
var longitudeIm = myLocation.Result.Longitude;
var pin1 = new Pin
{
Type = PinType.Place,
Position = new Position(latitudeIm, longitudeIm),
Title = "My Location"
};
customMap.Pins.Add(pin1);
}
My application breaks when I try this code var latitudeIm = myLocation.Result.Latitude;
I guess since I have a async task the result must be awaited. Any idea how can I use the public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation() data in my view?
You should use await for async method;
var myLocation = await ts.GetDeviceCurrentLocation();
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;
You should decorate all methods as async completely. If you don't able to apply it (I wouldn't recommend it), you could use ConfigureAwait to prevent deadlock;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
var myLocation = ts.GetDeviceCurrentLocation().Result;//Also don't hit the Result twice
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;

Async function in Converting object to another object in c#

I would like to implement an async function in converting the object to another object then in saving to the database.
public List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
ConvertToORouterOrdersAsync(tgOrders);
return ConvertToORouterOrdersCount(tgOrders);
}
I would like this method ConvertToORouterOrdersAsync(tgOrders); will run in the background and will return the Count of Orders from this ConvertToORouterOrdersCount(tgOrders) before the conversion is done.
Please help me to change the implementation to asynchronous.
public async void ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
To really have a advantage of the async and await the underlying calls should have async versions, for example the database calls should be async, don't know if you use EF or just plain SqlCommand but both have async versions of their calls.
Other calls that can be async is HTTP calls.
I have edited youre code with the assumption you are able to convert the underlying code to async.
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = await _requestHelper.GetHttpResponseAsync("orders" + filters).ConfigureAwait(false);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return await ConvertToORouterOrdersCountAsync(tgOrders).ConfigureAwait(false);
}
public async Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrderAsync(order.OrderId, base.StoreId).ConfigureAwait(false);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
await orderMgr.AddAsync(order).ConfigureAwait(false);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
Or if you just want to run the code in the background you can also just wrap it in a Task.Run
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return ConvertToORouterOrdersCount(tgOrders);
}
public Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
return Task.Run(() =>
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
});
}

Categories

Resources