Home > Blockchain >  My async func inside for loop is not working
My async func inside for loop is not working

Time:11-26

I have a code that gets all Item Prices from a database and then makes an API call to update them.

For some reason, loop inside my Button1_click function doesn't work but similar code without the loop on Button2_click will work fine. I cant understand why.

I can see the results of the API calls in the output. It seems like API is called but the price is never updated.

It is my first time dealing with Async functions and Task so I m a newbie at this.

    protected async void Button1_Click(object sender, EventArgs e)
    {
        dt = DB_GetItemPrice();

        for (int i = 0; i < dt.Rows.Count; i  )        
        {
            var task = SendRequestAsync(dt.Rows[i]);
            var items = await task;
            Debug.WriteLine(task.Result);
        }            

    }
    protected async void Button2_Click(object sender, EventArgs e)
    {
        dt = DB_GetItemPrice();

        var dr = dt.Rows[0];
        var task = SendRequestAsync(dr);
        var items = await task;
        Debug.WriteLine(task.Result);

    }
    protected DataTable DB_GetItemPrice()
    {
        var db = PSystem.DataHelp.Database.Application;
        var con = new DbConnection(db, ConnectionState.Open);
        var st =
            "SELECT * "  
            "FROM item_discount ";
        var cmd = new PSystem.DataHelp.DbCommand(st, con);

        using (var reader = cmd.ExecuteReader())
        {
            var dt = PSystem.DataHelp.DbManager.GetDataTable(reader);
            if (dt == null || dt.Rows.Count < 1)
                return null;
            return dt;                 
        }
    }

    private async Task<string> SendRequestAsync(DataRow dr)
    {
        string APICall;
        string OrderID = ((long)dr["OrderID"]).ToString();
        string GoodsID = ((long)dr["GoodsID"]).ToString();
        string NewPrice = ((long)dr["NewPrice"]).ToString();
        Debug.WriteLine(OrderID   "  ,"   GoodsID   "  ,"   NewPrice);
        APICall = "myAPIAdress?"   "&Param0="   GoodsID    ","   3   ","   NewPrice   ","   1   ","   OrderID   ",,";

        using (var wc = new System.Net.WebClient())
        {
            var Message = await wc.DownloadStringTaskAsync(APICall).ConfigureAwait(false);
            return Message;
        }

    } 

CodePudding user response:

Found out that my original code is working fine.

Probably API I tried to request has some sort of rate limiting or such. When I just give a second delay in between each tasks using await Task.Delay(1000), it works fine.

CodePudding user response:

I think your problem is the ConfigureAwait(false) in your SendRequestAsync method.

Try and remove that. You should not use ConfigureAwait(false) in your UI sync context.

Read here for details

  • Related