Async await how to use return values

后端 未结 4 2010
猫巷女王i
猫巷女王i 2021-02-04 00:41

I have a windows service that I have inherited from another developer, it runs very slow and has numerous slow call to the eBay API. I wish to speed it up without too much refac

4条回答
  •  有刺的猬
    2021-02-04 01:08

    Your async method lacks of await operators and will run synchronously. while you are calling non blocking API you could use Task.Run() to do cpu-bound work on background thread.

    public async Task ProcessAdditionalProductDetialsAsync(ItemType oItem)
    {
        return await Task.Run(() =>
        {
            String additionalProductDetails = string.Empty;
    
            if (oItem.ItemSpecifics.Count > 0)
            {
                foreach (NameValueListType nvl in oItem.ItemSpecifics)
                {
                    if (nvl.Value.Count > 0)
                    {
                        foreach (string s in nvl.Value)
                        {
                            additionalProductDetails += "
  • " + nvl.Name + ": " + s + "
  • "; } } } } return additionalProductDetails; }); }

    and get result

    var detail = await ProcessAdditionalProductDetialsAsync(itemType);
    var result = ProcessAdditionalProductDetialsAsync(itemType).Result;
    

提交回复
热议问题