Loop through synchronous list in asynchronous function

Yusuf 691 Reputation points
2022-07-22T06:52:33.01+00:00

Hi,

How can to loop through a synchronous list in an asynchronous function ?

 private  void Button_Clicked(object sender, EventArgs e)  
    {  
        FirebaseHelper firebaseHelper = new FirebaseHelper();  
        var books = firebaseHelper.GetAllBooksAsync();  
        foreach (var book in await books)     // CS4033  
        {  
            Debug.WriteLine(book.Title);  
  
        }  
    }  

I don't want to use await and the function must be asynchronous.
Thank you in advance.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,927 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,309 questions
{count} votes

Accepted answer
  1. ShuaiHua Du 636 Reputation points
    2022-07-24T13:34:24.627+00:00

    You can try the code below:

    private void Button_Clicked(object sender, EventArgs e)  
    {  
        Task.Run(() =>  
        {  
            FirebaseHelper firebaseHelper = new FirebaseHelper();  
            var books = firebaseHelper.GetAllBooksAsync();  
            foreach (var book in books)     // CS4033  
            {  
                Debug.WriteLine(book.Title);  
            }  
        });  
    }  
    

    If right, please accept.
    Enjoy Programming!!!

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-07-22T09:13:26.303+00:00

    @Yusuf , you could try to use Task<TResult>.Result Property to get list from the Task.

    Here is a code example you could refer to.

    private  void Button_Clicked(object sender, EventArgs e)  
        {  
            FirebaseHelper firebaseHelper = new FirebaseHelper();  
            var books = firebaseHelper.GetAllBooksAsync();  
            foreach (var book in  books.Result)     // change books to books.Result  
            {  
                Debug.WriteLine(book.Title);  
      
            }  
        }  
    

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Yusuf 691 Reputation points
    2022-07-24T02:06:26.017+00:00

    Thanks @Jack J Jun , the error has been solved but now the runtime error is happening.

    The thread 0x37c0 has exited with code 0 (0x0).

    ----------

    output:
    file:https://github.com/devenv2/MauiApp5/blob/master/MauiApp5/TextFile1.txt

    0 comments No comments