task result to list c#

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

task result to list c#

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Python questions
  • View PHP questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

task result to list c#

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

task result to list c#

task result to list c#

C# get results from Task.WhenAll

The C# method Task.WhenAll can run a bunch of async methods in parallel and returns when every one finished.

But how do you collect the return values?

UPDATED 2023-02-15 : Updated code based on comments. Thx for all the suggestions.

Imagine that you have this pseudo-async-method:

And you wish to call that method 20 times, and then collect all the results in a list?

That is a 3 step rocket:

  • Create a list of tasks to run
  • Run the tasks in parallel using Task.WhenAll .
  • Iterate over the results

WHY DID I UPDATE THE CODE?

In my previous example, I forgot to include the return type when creating the list of tasks:

When you do not include the type that the task returns, the Task.WhenAll returns void, and you need another loop to collect the return types directly from the tasks themselves.

Thanks for all the comments. And happy coding.

MORE TO READ:

  • Task.WhenAll from microsoft
  • Run tasks in parallel using .NET Core, C# and async coding by briancaos
  • Using C# HttpClient from Sync and Async code by briancaos
  • Awaiting multiple Tasks with different results from stackoverflow
  • Get the result of multiple tasks in a ValueTuple and WhenAll by Gérald Barré
  • Using Task.WhenAny And Task.WhenAll by Hamid Mosalla
  • Run parallel tasks in batches using .NET Core, C# and Async coding by briancaos

Share this:

' src=

About briancaos

6 responses to c# get results from task.whenall.

' src=

// This is a bit nicer (and shorter) I think

// Create a list of tasks to run List<Task> tasks = new List<Task>(); foreach (int i=0;i<20;i++) { tasks.Add(GetAsync(i)); }

// Run the tasks in parallel, and // wait until all have been run // collecting the results at the same time var results = await Task.WhenAll(tasks);

// the above is an array, but if a list is required this line could be used instead: // var results = (await Task.WhenAll(tasks)).ToList();

' src=

// This is a bit nicer (and shorter) I think – my previous posting // looked like the Task lost its generic parameter, string

// Create a list of tasks and start them running List<Task> tasks = new List<Task>(); foreach (int i=0;i<20;i++) { tasks.Add(GetAsync(i)); }

// Wait until the running tasks have been run // collecting the results at the same time var results = await Task.WhenAll(tasks);

' src=

Task.WhenAll does not run tasks!! But for collecting all the results in one array, it is fine. var results = await Task.WhenAll(tasks);

' src=

I like this without loop an new list if error (int.MinValue) exist

int someError = (from err in ListTasks let CathError = ((Task)err).Result where CathError == int.MinValue select err

I am sorry i was using Count() and i was forgrget write all code . int someError = (from err in ListTasks let CathError = ((Task)err).Result where CathError == int.MinValue select err).Count()

' src=

Others have pointed this out already, but I’d like to drive the point home: _await_ in combination with Task.WhenAll returns an array, so why on earth would you go out of your way to create a list? I prefer not to use a specific type to var, so the easy and efficient way to do this would be to declare and assign an array: string[] results = await Task.WhenAll(tasks);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • Search for:

Sitecore MVP 10 year anniversary

Legal Notice

  • C# DateTime to UNIX timestamps
  • C# get results from Task.WhenAll
  • C# Azure Table Storage QueryAsync, Paging and Filtering
  • C# Use HttpClient to GET JSON from API endpoint
  • C# HttpClient POST or PUT Json with content type application/json
  • C# List Batch - Breaking an IEnumerable into batches with .NET
  • Run tasks in parallel using .NET Core, C# and async coding
  • Entries feed
  • Comments feed
  • WordPress.com
  • Sitecore and .net
  • Alan Coates
  • Andy Burns' Blog
  • Best Sitecore Blogs
  • Core Sampler Sitecore Podcast
  • Corey Smith
  • Dan Solovay Explorations
  • Göran Halvarsson Visions In Code
  • Jeremy Davis Sitecore, C# and web development
  • Kelly Rusk The Bits That Byte
  • Martin Miles Experience Sitecore
  • Sitecore Basics
  • Sitecore Competencies
  • Sitecore Docs
  • Sitecore Notes by Stelio Di Bello
  • Thomas Stern iStern
  • Viet Hoang Walking on clouds
  • Application Insights
  • Asynchronous
  • Azure Function
  • Azure Queue
  • Configuration
  • Dependency Injection
  • ExpandoObject
  • Experience Editor
  • Google maps
  • httpRequestBegin
  • IHttpClientFactory
  • LinkManager
  • media library
  • Page Editor
  • Performance
  • Personalization
  • Scheduled Tasks
  • Session state
  • ShowModalDialog
  • Usercontrol
  • YetAnotherForum

' src=

  • Already have a WordPress.com account? Log in now.
  • Follow Following
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Process asynchronous tasks as they complete (C#)

  • 2 contributors

By using Task.WhenAny , you can start multiple tasks at the same time and process them one by one as they're completed rather than process them in the order in which they're started.

The following example uses a query to create a collection of tasks. Each task downloads the contents of a specified website. In each iteration of a while loop, an awaited call to WhenAny returns the task in the collection of tasks that finishes its download first. That task is removed from the collection and processed. The loop repeats until the collection contains no more tasks.

Prerequisites

You can follow this tutorial by using one of the following options:

  • Visual Studio 2022 with the .NET desktop development workload installed. The .NET SDK is automatically installed when you select this workload.
  • The .NET SDK with a code editor of your choice, such as Visual Studio Code .

Create example application

Create a new .NET Core console application. You can create one by using the dotnet new console command or from Visual Studio.

Open the Program.cs file in your code editor, and replace the existing code with this code:

In the Program class definition, add the following two fields:

The HttpClient exposes the ability to send HTTP requests and receive HTTP responses. The s_urlList holds all of the URLs that the application plans to process.

Update application entry point

The main entry point into the console application is the Main method. Replace the existing method with the following:

The updated Main method is now considered an Async main , which allows for an asynchronous entry point into the executable. It is expressed as a call to SumPageSizesAsync .

Create the asynchronous sum page sizes method

Below the Main method, add the SumPageSizesAsync method:

The while loop removes one of the tasks in each iteration. After every task has completed, the loop ends. The method starts by instantiating and starting a Stopwatch . It then includes a query that, when executed, creates a collection of tasks. Each call to ProcessUrlAsync in the following code returns a Task<TResult> , where TResult is an integer:

Due to deferred execution with the LINQ, you call Enumerable.ToList to start each task.

The while loop performs the following steps for each task in the collection:

Awaits a call to WhenAny to identify the first task in the collection that has finished its download.

Removes that task from the collection.

Awaits finishedTask , which is returned by a call to ProcessUrlAsync . The finishedTask variable is a Task<TResult> where TResult is an integer. The task is already complete, but you await it to retrieve the length of the downloaded website, as the following example shows. If the task is faulted, await will throw the first child exception stored in the AggregateException , unlike reading the Task<TResult>.Result property, which would throw the AggregateException .

Add process method

Add the following ProcessUrlAsync method below the SumPageSizesAsync method:

For any given URL, the method will use the client instance provided to get the response as a byte[] . The length is returned after the URL and length is written to the console.

Run the program several times to verify that the downloaded lengths don't always appear in the same order.

You can use WhenAny in a loop, as described in the example, to solve problems that involve a small number of tasks. However, other approaches are more efficient if you have a large number of tasks to process. For more information and examples, see Processing tasks as they complete .

Complete example

The following code is the complete text of the Program.cs file for the example.

  • Asynchronous programming with async and await (C#)

Submit and view feedback for

Additional resources

c# return task list

Pleased to see you again.

  • Master useful skills
  • Improve learning outcomes
  • Share your knowledge

Create a Free Account

Mark the violation.

Getting the result from a list of tasks

Looking for more? Join the community!

Dot Net Tutorials

How to Return a Value from Task in C#

Back to: C#.NET Tutorials For Beginners and Professionals

How to Return a Value from Task in C# with Examples

In this article, I am going to discuss How to Return a Value from a Task in C# with Examples. Please read our previous article where we discussed Task in C# with Examples. At the end of this article, you will understand How to Return a Value from a Task in C# with examples.

How to Return a Value from a Task in C#?

The .NET Framework also provides a generic version of the Task class i.e. Task<T>. Using this Task<T> class we can return data or values from a task. In Task<T>, T represents the data type that you want to return as a result of the task. With Task<T>, we have the representation of an asynchronous method that is going to return something in the future. That something could be a string, a number, a class, etc.

Example to Understand Task<T> in C#:

Let us understand this with an example. What are we going to do is, we are going to communicate with a Web API that we are going to build and we will try to retrieve the message that we receive from the Web API.

Creating ASP.NET Web API Project

Open Visual Studio and creates a new ASP.NET Web API Project. If you are new to ASP.NET Web API, then please have a look at our ASP.NET Web API Tutorials. Here, we are creating an Empty Web API Project with the name WebAPIDemo. Once we created the Web API Project then add a Web API Controller with the name GreetingsController inside the Controllers folder. Once you add the GreetingsController then copy and paste the following code inside it.

Now, run the Web API application, and you can access the GetGreetings resource using the URL api/greetings/name as shown in the below image. Please note the port number, it might be different in your case.

Example to Understand Task<T> in C#

Once you run the Web API Project, then you can access the above resource from anywhere. You can access it from a web browser, you can access using postman and fiddler, and you can also access it from other web, windows, and console application. In our example, we are going to access this from our Console application.

The idea is that since the Web API is external to our Console application. So, talking to the Web API is an IO operation, which means that we will have to use or we should use Asynchronous Programming.

Calling Web API HTTP Request from Console Application

Now, we will make an HTTP Request to the Web API (External Resource) from our Console Application. Please copy the endpoint address of the Web API. And then modify the code as follows. You need to replace the port number on which your Web API application is running. In the below example, we are making an asynchronous call to the Web API.

Output: Before running the console application, please make sure your web application is running. Once your Web API Application is running, then run the console application. It will ask you to enter your name. Once you enter the name, press the enter key and you will see the following output.

How to Return a Value from a Task in C# with Examples

The point that you need to remember is that if you are writing any asynchronous method, then you can use Task as the return type if it is not returning anything or you can use Task<T> when your method returns something. Here T can be anything like string, integer, Class, etc.

And we also saw that by using await, we are suspending the execution of the current thread. So we are freeing the thread so that the thread can be used in other parts of the application. And once we have a response, for example, from our Web API, then it will use the thread again to execute the rest part of the method.

C# Task with Errors:

So far, every task that we have executed has been completed successfully. And, in real life, this may not be the case always. Sometimes errors will happen. For example, maybe we were wrong in the URL. In this case, we will get a 404 error. Let us understand this with an error. In the URL, I have changed greetings to greetings2 as shown in the below code. Further, I have included the response.EnsureSuccessStatusCode(); statement to throw 404 error.

Output: With the above changes in place now we run the application, before that make sure the Web API Application is running. Enter the name and press the enter button as shown in the below image.

C# Task with Errors

Once you enter your name and press the enter button, then you will get the following unhandled exception.

C# Task with Errors Examples

Please observe here we are getting 404 Not Found HttpRequestException. This is a bad user experience. The user should not see this message. If any exception occurred then instead of showing the exception details, we should show some generic error message. Let us see how we can do this. Within the SomeMethod we need to use the Try and Catch block to handle the unhandled exception which is shown in the below example.

How to Return a Value from a Task in C# with Examples

Now, we are not getting that exception rather we seeing some generic message on the console. This is different than having an unhandled exception. So, here we completely control what was going to happen if we get an exception.

What happens if we omit the await keyword while calling the Greetings method?

Something that you need to keep in mind is that if you don’t await the task, then the exception will not be thrown to the caller method i.e. the method from where we called the async method. In our example, it will not throw the exception to the SomeMethod. Let’s see that. Let’s remove the await keyword and the printing of the greeting statement inside the SomeMethod as shown in the below example and run the application.

Now, when you run the application, you will not get the exception. You will get the following output which does execute the catch block.

What happens if we omit the await keyword while calling the Greetings method?

Why we did not get the exception?

Please have a look at the below image. When an Exception has occurred inside an async method, that exception is encapsulated inside the Task.

Why we did not get the exception?

If you want to unwrap the exception then you need to use await as shown in the below image. If you are not using await, then you will never get the exception.

Why we did not get the exception?

Note: We can catch exceptions by using a simple try-catch block. But if we never await the task, then even if we have an exception, the exception is not going to be thrown. So, if you want to be notified about the exceptions that you may have, you need to await the task.

Example to Understand How to Return Complex Type Value From a Task in C#:

In the below example, we are returning a Complex type.

task result to list c#

In the next article, I am going to discuss How to Execute Multiple Tasks in C# with Examples. Here, in this article, I try to explain How to Return a Value from a Task in C# with Examples. I hope you enjoy this Task that Returns a Value in C# with Examples article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

1 thought on “How to Return a Value from Task in C#”

task result to list c#

Guys, Please give your valuable feedback. And also, give your suggestions about this How to Return a Value from a Task in C# concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to How to Return a Value from a Task in C#, you can also share the same.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

IMAGES

  1. Tasks in C#

    task result to list c#

  2. Browsing Task Logs

    task result to list c#

  3. How to Control the Result of a Task in C#

    task result to list c#

  4. azure

    task result to list c#

  5. Create Task Scheduler In C# And.NET

    task result to list c#

  6. How to Control the Result of a Task in C#

    task result to list c#

VIDEO

  1. SECRETS OF C#

  2. Bigg Boss Tamil Season 7

  3. 102 C# C Sharp WPF GUI DatePicker control

  4. C# Tutorial

  5. C# List Add & AddRange Methods #shorts

  6. ToDo List C# Sql Crud

COMMENTS

  1. Free vs Paid Business Listings: Why Adding for Free Can Still Drive Results

    In today’s digital age, having an online presence is crucial for any business. One of the most effective ways to increase visibility and drive more customers is by adding your business to online directories.

  2. Get the Best Deals on Rental Listings Near You

    Renting a home or apartment can be a daunting task. With so many rental listings available, it can be difficult to find the best deals. However, with the right resources and strategies, you can find great rental listings near you at an affo...

  3. Get a Head Start on Your Search for Rental Listings Near You

    Are you looking for a rental property near you? Finding the right place can be a daunting task, but with the right resources and information, you can get a head start on your search. Here are some tips to help you find rental listings near ...

  4. Return list from async/await method

    The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded

  5. c# How to add task to list and call all the tasks at last

    WriteLine( "This is task 1" ); Action action2 = ( ) => Console.WriteLine( "This is task 2" ); Action action3 = ( ) => Console.WriteLine( "This

  6. Task<TResult>.Result Property

    List<Task<long>>(); for (int ctr = 1;

  7. Re: Run List Of Tasks, Then Get All Results

    QualificationTestResult[] results = Task.WhenAll(tasks).GetAwaiter().GetResult();. "These people looked deep within my soul and assigned me a number based on

  8. C# get results from Task.WhenAll

    Create a list of tasks to run; Run the tasks in parallel using Task.WhenAll. Iterate over the results. 1. 2.

  9. Создание цепочки задач с помощью задач продолжения

    "afternoon" : "morning"; }); await task.ContinueWith( antecedent => { Console.WriteLine($"Good {antecedent.Result}!"); Console.WriteLine(

  10. Process asynchronous tasks as they complete (C#)

    List<Task<int>> downloadTasks = downloadTasksQuery.ToList();. The ... Result property, which would throw the AggregateException . C# Copy.

  11. c# return task list Code Example

    private async Task&lt;List&lt;Item&gt;&gt; GetListAsync(){ //Create a list object and assign it to a new task //which returns your lis...

  12. Getting the result from a list of tasks

    Its been a minute since I have done async methods but i know i can do a list of tasks I just think I'm using them wrong.

  13. c#

    public static async Task<List<T>> AsListAsync<T>(this Task<IEnumerable<T>> task) => await task is List<T> list ? list : new List<T>(task.Result)

  14. How to Return a Value from a Task in C# with Examples

    Using this Task<T> class we can return data or values from a task. In Task<T>, T represents the data type that you want to return as a result of