将对象转换为c#中的另一个对象的异步函数

时间:2017-02-08 08:59:42

标签: c# asynchronous

我想在将对象转换为另一个对象然后保存到数据库时实现异步函数。

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);
}

我希望此方法ConvertToORouterOrdersAsync(tgOrders);将在后台运行,并会在转换完成之前从此ConvertToORouterOrdersCount(tgOrders)返回订单计数。

请帮我将实现更改为异步。

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);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

要真正拥有异步并等待底层调用应该有异步版本,例如数据库调用应该是异步的,不知道你是使用EF还是只是普通function recurse($newArr, $key=NULL) { if($key !== NULL) { foreach ($newArr[$key] as $k=>$v) { echo '<li>Destination: ' . $v . '</li>'; } echo '</ul>'; } else { foreach ($newArr as $k=>$v) { echo 'Source: ' . $k . '<br><ul>'; recurse($newArr, $k); } } } 但是两者都有异步他们的电话版本。

其他可以异步的调用是HTTP调用。

我编辑了你的代码,假设你能够将底层代码转换为异步。

SqlCommand

或者,如果您只想在后台运行代码,您也可以将其包装在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 = 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);
        }
    }
}