foreach problem in async method

Posted 24 days ago by igorbaldacci

Hi guys,
I'm new here so hello to everybody!

In my Blazor project, I have implemented the above method to update database in a component (.razor) . It read a .txt file, and in a foreach loop it call a post web API to save data in the database:

   private async Task updateDatabaseAsync()
            [ ... code ... ]
            // Update Database (post API)
            int intTotal = 11;
            List<string> lstMyList = File.ReadLines(strPathNameText).Reverse().Take(intTotal).Reverse().ToList();
            string sep = "\t";
            foreach (string txtMyDataInList in lstMyList)
                MyData newData = new MyData();
                newData.TypeData01 = txtMyDataInList.Split(separator: sep.ToCharArray())[0];
                newData.TypeData01 = txtMyDataInList.Split(separator: sep.ToCharArray())[1];
                newData.TypeData01 = txtMyDataInList.Split(separator: sep.ToCharArray())[2];
                await MyService.PostUpdateDatabase(newData);
        catch (Exception ex)
            var errorMessage = ex.Message;

The method works fine. The problem started when I have moved this method inside a generic class, in order to use it in different parts of my code.

Inside the generic class the method doesn't works! This is the same method, I haven't changed nothing, but in the line were the  web api is colled I receive an error: "object reference not set to an instance of an object".

I have changed the method in different way, instead of the foreach loop. I have used the "Task.WhenAll(tasks);", or Parallel, but nothing I receive the same error.

Any idea to understand where the problem is? Thanks in advance for every kind of help.




  • 0

    Friends, I found the solution by myself. The problem were in the MyService. I have injected the service in my class in wrong way. 

    I need to study more of Blazor, I think.

    Best regards to all.


    Posted 23 days ago by igorbaldacci
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 1
An error has occurred. This application may no longer respond until reloaded. Reload 🗙