Blog about Microsoft technologies (.NET, ASP.NET Core, Blazor, EF Core, WPF, TypeScript, etc.)

Get the result of multiple tasks in a ValueTuple and WhenAll

Dot Net Tutorials

How to Control the Result of a Task in C#

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

How to Control the Result of a Task in C# using TaskCompletionSource

In this article, I am going to discuss How to Control the Result of a Task in C# using TaskCompletionSource with Examples. Please read our previous article where we discussed Only One Pattern in C# Asynchronous Programming with Examples.

How to Control the Result of a Task in C#?

So far, we have worked with tasks, and task status depends on an event. For example, if we make an HTTP request or if we make an Async method call, then the status of the task is associated with what happens with the HTTP Request or with the Async Method call, whether it is successful, or there is an exception or the operation is canceled using a cancellation token. With TaskCompletionSource , we can create a task for which we are the ones who will control its status, whether it is successful, canceled, or if it’s thrown an exception.

Constructors, Methods, and Properties of TaskCompletionSource class in C#:

If you go to the definition of TaskCompletionSource class in C#, you will see the following. You can see it is a generic class.

Constructors, Methods, and Properties of TaskCompletionSource class in C#

Constructors of TaskCompletionSource class:

The TaskCompletionSource class in C# provides the following 4 constructors that we can use to create an instance of the TaskCompletionSource class.

  • TaskCompletionSource(): It creates a System.Threading.Tasks.TaskCompletionSource object.
  • TaskCompletionSource(TaskCreationOptions creationOptions): It creates a TaskCompletionSource with the specified options. Here, the parameter creationOptions specify the options to use when creating the underlying Task.
  • TaskCompletionSource(object state): It creates a TaskCompletionSource with the specified state. Here, the parameter state specifies the state to use as the underlying Task’s AsyncState.
  • TaskCompletionSource(object state, TaskCreationOptions creationOptions): It creates a TaskCompletionSource with the specified state and options. Here, the parameter state specifies the state to use as the underlying Task’s AsyncState and the parameter creationOptions specify the options to use when creating the underlying Task.

Property of TaskCompletionSource class in C#:

The TaskCompletionSource class in C# provides the following property.

  • Task<TResult> Task { get; } : It returns the System.Threading.Tasks.Task created by this TaskCompletionSource.

Methods of TaskCompletionSource class in C#:

The TaskCompletionSource class in C# provides the following methods.

  • SetCanceled(): This method is used to set the underlying Task into the Canceled state.
  • SetException(Exception exception): This method is used to set the underlying Task into the Faulted State and binds it to a specified exception. Here, the parameter exception specifies the exception to binding to this Task.
  • SetException(IEnumerable<Exception> exceptions): This method is used to set the underlying Task into the Faulted State and binds a collection of exception objects to it. Here, the parameter exception specifies the collection of exceptions to bind to this Task.
  • SetResult(TResult result): This method is used to set the underlying Task into the RanToCompletion State. Here, the parameter result specifies the result value to bind to this Task.

Example to Understand How to Control the Result of a Task in C#?

Let us understand this with an example. Let’s create a method that will return a task, but it will be a task in which we will control its status. For a better understanding, please have a look at the below image. Here, we have created one method which is returning a Task and taking a string input value. First, we created an instance of the TaskCompletionSource class using one of the overloaded versions of the Constructor. Then we are checking the string value using if-else statements. If the input string value is 1 then we are calling the SetResult method on the TaskCompletionSource instance, this method will set the state of the Task (the task holds by the TaskCompletionSource object) to RanToCompletion. Next, if the string value is 2, then we are calling the SetCanceled method which will set the state of the Task to Canceled. If the value is neither 2 nor 3, then we are calling the SetException method by passing an exception object which will set the state of the Task to Faulted. Finally, we are returning the task by calling the Task property of the TaskCompletionSource class.

Example to Understand How to Control the Result of a Task in C#?

Next, in order to check whether the task is completed, faulted, or canceled, we are going to use the following three properties of the Task class.

  • IsCompleted { get; }: It returns true if the task has been completed; otherwise false.
  • IsCanceled { get; }: It returns true if the task has been completed due to being canceled; otherwise false.
  • IsFaulted { get; }: It returns true if the task has thrown an unhandled exception; otherwise false.

For this, we are creating the following method. From this method, we are calling the EvaluateValue method. The EvaluateValue method returns one task whose status we managed. Remember, if we are passing 2, then we are throwing an exception. Even if we pass 2, then also it will throw a standard task canceled exception. So, to handle those exceptions we are using the try-catch block and also printing the error message on the console window.

Following is the Complete Example Code:

Now, run the application and enter the value as 1. You will get the following output. Is Completed as true and Is canceled and Is faulted as False.

Now, again run the application and enter the value as 2. You will get the following output. Is Completed and Is canceled as True and Is faulted as False. As it is canceled so it will throw a task canceled exception that you can see in the Exception message.

Now, again run the application and enter the value as 3. You will get the following output. Is Completed as True, Is canceled as False and Is Faulted as True. As we throw an exception, so you can that exception message.

So, you can see with TaskCompletionSource, we have complete control over the status of the task.

Example of TaskCompletionSource With Return Value

In the previous example, if you remember we have set null, in the SetResult method. It is also possible to return some value. Let us say we want to return a string value. Then we need to pass the string value to the SetResult method. Apart from this, we need to do two more changes, First, the return type of the method will change from Task to Task<string>, and while creating the instance if the TaskCompletionSource, instead of object we need to pass a string. The following example exactly does the same.

Run the above code and enter the value as 1 and then you will get the following output. You can observe the Result.

In the next article, I am going to discuss Task-based Asynchronous Programming in C# with Examples. Here, in this article, I try to explain How to Control the Result of a Task in C# using TaskCompletionSource with Examples. I hope you enjoy this How to Control the Result of a Task in C# with Examples using TaskCompletionSource article.

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.

3 thoughts on “How to Control the Result of a Task in C#”

Guys, Please give your valuable feedback. And also, give your suggestions about this How to Control the Result of 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 Control the Result of a Task in C#, you can also share the same.

Hello, Just a question: do we really need to awit for ttask in this code below ?

try { Console.WriteLine($”Is Completed: {task.IsCompleted}”); Console.WriteLine($”Is IsCanceled: {task.IsCanceled}”); Console.WriteLine($”Is IsFaulted: {task.IsFaulted}”); await task; } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(“EvaluateValue Completed”);

If you are not awaiting the task, then it will not wait till the task is completed. In that case, if any exception occurs, your application will not handle it.

Leave a Reply Cancel reply

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

C# - How to return a completed Task with or without a result

When using tasks you at some point come across having to return a Task without actually having a Task to return. The usual case is in a unit test where you want to stub or mock something.

Return a completed task with a result

I previously made a post on how to do this here . In short you can use Task.FromResult() to create a completed Task with a result of your choice. Below is an example:

You can either await the above (preferred) or use .Result to get the string SomeResult .

Create a completed task without a result

Sometimes you may just need to return a task to fill a contract in a method. You can do this by using Task.Completed task:

That is all there is to it, you can also await the above if you need to.

If you are on an ancient version of .Net you can also implicitly cast a Task with a result to a regular task and return that:

completedTask in the above will be a regular Task that is completed.

That is it!

I hope you found this helpful, please leave a comment down below if it was!

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Using task list values as variables

How to use task list command in batch file and use results as variables. For example, close chrome.exe if it is open

This is my experiment;

please help but can't succeed

guapo's user avatar

  • 1 Your batch iterates tasklist output line by line and then does nothing with it : empty pair of parentheses. Outside the scope of the for command (same line/or code block) the variable %%a is invalid. See tasklist /? or view online –  LotPings Aug 2, 2019 at 14:41
  • First of all, my English is not very good. What I want to do is use the tasklist results as variables –  guapo Aug 2, 2019 at 16:28

You should develop your batch step by step, starting in an open cmd window.

To process this sample output with a for /f you will have to first eliminate irrelevant lines by filtering with a findstr or with an if.

for /f uses by default space/tab as delimiters and only token=1. As we need the PID which is the 2nd token:

Returns the bar PID numbers you are after.

Just don't echo but use taskkill /PID %%a to remove all chrome.exe processes.

The if variant:

LotPings's user avatar

  • So how can I use it with IF ELSE –  guapo Aug 2, 2019 at 18:50
  • See appendum to the answer. –  LotPings Aug 2, 2019 at 19:51
  • Thanks, man, that was exactly what I was looking for. –  guapo Aug 3, 2019 at 8:51

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged batch cmd.exe ..

  • The Overflow Blog
  • How to train your dream machine
  • You should keep a developer’s journal
  • Featured on Meta
  • Our Partnership with OpenAI
  • What deliverables would you like to see out of a working group?

Hot Network Questions

  • Could you kill someone using Enchantment School Wizard's Hypnotic Gaze forever?
  • Why are ND filters used in moon photography
  • Inserting image as character
  • When using the method of substituting variables to find the limit, why can we still use the original numbers that need to be approximated?
  • What does ‘D’ in GADP (glyceraldehyde 3-phosphate) stand for?
  • How is the Kohen allowed to reply "Bruchim Tihyu" after Birchas Kohanim?
  • Nontrivial advantages of thinking of groups as groupoids with one object?
  • Decouple game entity from its owner when logic depends on it
  • tips for future philosophy student
  • 60's or 70's scifi tv episode where a robot was stuck repeating an out-of-date action
  • What are the minimum system requirements to run GW-BASIC?
  • TikZ: How find min, max of x-values in list of coordinate pairs?
  • Short fiction about a planet with two sentient species, one having enslaved the other one
  • How to name a TikZ path?
  • Windows Terminal automatic switch dark/light theme based on Windows settings
  • Can we install and run Ubuntu WSL for ARM on x86_64 windows machine?
  • Are Eilenberg-MacLane spaces limits of manifolds?
  • Which duplo digit is 6 or 9?
  • Steenrod powers of the Thom class
  • Can Warlocks take feats that require the "Spellcasting Feature"?
  • New record for minimally clued 7x7 Hidato (now with 6 clues!)
  • Functional equation arising in computing an integral
  • Should I wait to send a revised manuscript?
  • How Much Rehab/Partial Rebuild Can Be Done While Keeping Existing Mortgage?

task list result

Code Maze

  • Blazor WASM 🔥
  • ASP.NET Core Series
  • GraphQL ASP.NET Core
  • ASP.NET Core MVC Series
  • Testing ASP.NET Core Applications
  • EF Core Series
  • HttpClient with ASP.NET Core
  • Azure with ASP.NET Core
  • ASP.NET Core Identity Series
  • IdentityServer4, OAuth, OIDC Series
  • Angular with ASP.NET Core Identity
  • Blazor WebAssembly
  • .NET Collections
  • SOLID Principles in C#
  • ASP.NET Core Web API Best Practices
  • Top REST API Best Practices
  • Angular Development Best Practices
  • 10 Things You Should Avoid in Your ASP.NET Core Controllers
  • C# Back to Basics
  • C# Intermediate
  • Design Patterns in C#
  • Sorting Algorithms in C#
  • Docker Series
  • Angular Series
  • Angular Material Series
  • HTTP Series
  • .NET/C# Author
  • .NET/C# Editor
  • Our Editors
  • Leave Us a Review
  • Code Maze Reviews

Select Page

How to Execute Multiple Tasks Asynchronously in C#

Posted by Code Maze | Updated Date Aug 17, 2022 | 4

How to Execute Multiple Tasks Asynchronously in C#

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we are going to learn how to execute multiple tasks in C# in sequence and parallel. By using async/await , we avoid performance bottlenecks and enhance the scalability of our application. Depending on the business logic, we may need to execute functional tasks either sequentially, or in parallel.

Let’s dive into it.

Creating a Demo REST API

Let’s consider that we are developing an application for employee management in an organization. The client/UI application consumes a REST-based API that will return the employee details, salary, and appraisal rating for an employee from three different endpoints.

Become a patron at Patreon!

Here, we will use a simple ASP.NET Core Web API. The controller actions in this Web API return static data for this demo:

Now, let’s take a look at the three endpoints with their response in the swagger documentation for this Web API:

We have made the Web API simple on purpose as we don’t want to deviate from the topic of this article by diving into the intricate implementation details of an ASP.NET Core Web API.

Execute Multiple Tasks in Sequence using async and await

The client application has an EmployeeProfile class which we use as a presentation model to the end-user:

Here, we override the ToString() method to append all the employee data to a single string for printing it to the console.

Since this class acts like a view model, the properties of this class are constructed from the contract classes:

The Executor class in the client application consolidates employee data from all three REST API endpoints while constructing the EmployeeProfile instance:

Here, we are executing the tasks for fetching employee details, salary, and rating in sequence using asynchronous programming .

First, we are awaiting the Task instance returned by the GetEmployeeDetails() method. Then, we do the same with  GetEmployeeSalary() in the continuation of the GetEmployeeDetails() method. Finally, we repeat the action with the GetEmployeeRating() method in the continuation of the GetEmployeeSalary() method. Hence, in this case, each task execution step waits for the previous step to finish without blocking the thread.

In these three methods ( GetEmployeeDetails() , GetEmployeeSalary() , GetEmployeeRating() ) all we do is send a simple HTTP request and process the response . Also, we are simulating a network latency in all three methods using the Task.Delay() method. Such delay is very common in enterprise-grade applications due to factors like slow database calls, geographic factors, etc.

You can find the implementation inside the EmployeeApiFacade class in the client project.

Typically, we do such sequential execution in a workflow where each task execution step is dependent on the previous one, unlike the above steps. However, here we are anyway doing it to demonstrate in a later section the performance improvement that we can achieve by executing these tasks in parallel.

Let’s now run the client application:

We get back the consolidated result. Let’s now see if we can improve the performance of this functionality.

Execute Multiple Tasks in Parallel using Task.WhenAll

Since the tasks for fetching employee details, salary and rating are independent of each other, it is easy to execute them in parallel to improve the overall performance of the workflow:

Here, we are not awaiting the Task instances from any of the methods which means that these methods will now return the Task instances instead of the result and will execute in parallel. However, we need to wait for all three methods to complete their execution before the consolidation of the result. This is achieved by using the WhenAll method from Task Parallel Library.

The Task.WhenAll method creates a Task that will be complete when all the supplied tasks have been completed. Once all three Tasks are complete, we await the individual Task instances to derive the result from them.

Alternatively, we can use the Result property from the Task instances instead of awaiting them to avoid some unnecessary state of machine-generated code during compilation:

Though using blocking code like .Result is not considered good practice under normal circumstances, in this case, it is perfectly safe to use it as all the tasks have finished execution by the time this line is executed. In fact, in this case, it is more beneficial to use this approach as it reduces the size of the compiled code.

Now, when we execute the client code, we get back the consolidated result but with an increase in the overall performance.

Improving the Exception Handling in Task.WhenAll

Handling exceptions play a major part in real-life application development. There is a problem in the above implementation in regards to handling exceptions. Let’s consider a scenario where both GetEmployeeDetails() and GetEmployeeSalary() methods throw exceptions:

In this case, we are only getting the first exception in the console and ignoring the other exception.

So, if other Task instances throw any exceptions, we will never know about it. If we want to get hold of all the exceptions for logging purposes, we need to handle Task.WhenAll a bit differently:

This method extends the Task.WhenAll method to return a ValueTuple with the results of the tasks. Most importantly, it also handles the issue with multiple exceptions by catching and rethrowing an aggregate exception on all tasks that are awaited.

Now, we can invoke the WhenAll method from the TaskExtensions class instead of the original Task.WhenAll in the calling method:

If we execute the client code now, we can see an aggregate exception in the console showing both exceptions:

Performance Comparison async/await vs. Task.WhenAll 

To compare the performance between the two approaches, we have run a benchmark with the default target count:

The ExecuteInParallel() method that uses Task.WhenAll clearly exhibits better overall performance compared to the ExecuteInSequence() method.

Sequential Task Execution using async, await, and foreach Loop

Let’s consider another business workflow where we need to invoke the same REST API endpoint multiple times. For example, invoking the /details/{id} endpoint to fetch details for three different employees. Once again, depending on the business case, we may have to do this either sequentially or in parallel.

To execute the tasks sequentially, we can use a foreach loop:

Here, for each employee id, we call the GetEmployeeDetails() method that invokes the /details/{id} endpoint in the REST API. We await the Task instance returned from the GetEmployeeDetails() method and then write the employee details to the console:

We see that all the tasks are executed. However, these tasks of fetching employee details for multiple employees can very easily be executed in parallel as they are independent of each other. So, executing them in parallel will improve the performance. Let’s see how we can achieve such improvement.

Parallel Tasks Execution using Parallel.Foreach

The Parallel.ForEach method executes a foreach operation in which the iterations may run in parallel.

Let’s re-write the example from the previous section using Parallel.ForEach :

We set the MaxDegreeOfParallelism property to 3. This property limits the number of concurrent operations by the Parallel.ForEach loop to the set value. By default, ForEach will utilize as many threads as the underlying scheduler provides. But, we are limiting this for better utilization of CPU resources in this demo as we have only 3 independent tasks.

Parallel.ForEach does not support asynchronous delegates. So, we are blocking the thread that executes the GetEmployeeDetails() method till it produces a result.

In many cases, Parallel.ForEach can provide significant performance improvements over ordinary sequential loops. However, the work of parallelizing the loop introduces complexity that can lead to problems that we don’t encounter in sequential code. In certain cases, a parallel loop might run slower than its sequential equivalent.

It is better to keep in mind the below points before using the Parallel loops:

  • Parallel loops are designed for CPU-intensive operations. It’s not always the best solution for I/O-bound operations
  • Parallel loops are not appropriate for asynchronous code flow
  • The degree of parallelism is completely dependent on the number of cores and CPU specifications so performance can vary

In the previous code block, each thread runs the independent I/O operations because of the lack of async support in the Parallel.ForEach . This is a big issue considering scalability and has the potential for thread pool starvation in an ASP.NET web application.

However, starting from .NET 6 we can use the Parallel.ForEachAsync method which is async aware.

Parallel Tasks Execution using Parallel.ForeachAsync

The Parallel.ForEachAsync executes a foreach operation on an IEnumerable<T> in which iterations may run in parallel. However, unlike the Parallel.ForEach , it returns a Task instance that represents the entire for-each operation. It also supports an async delegate. This was introduced recently as part of .NET 6.0

Now, let’s re-write the example from the previous section using Parallel.ForEachAsync :

Here, we set the MaxDegreeOfParallelism property to 3 like in the previous section for better optimization of CPU resources.

Now, on executing the client code, we see that the tasks are executed and  it  is approximately similar to the timing that we got using the Parallel.ForEach . 

Performance Comparison foreach vs. Parallel.ForEach vs. Parallel.ForEachAsync

Here also, we have run a benchmark with the default target count:

So, the Parallel.ForEach and the Parallel.ForEachAsync approaches perform better than the normal foreach . We see that there is not much difference in terms of execution time between the Parallel.ForEach and the Parallel.ForEachAsync . However, the scalability of Parallel.ForEachAsync is much higher considering that it is not blocking the individual threads anymore during the I/O operations. Hence, it minimizes the chances of thread pool starvation.

In this article, we have demonstrated a few scenarios where we may need to execute tasks in sequence and parallel. C# provides us with many approaches to achieve the same and we have covered most of them here. One must keep in mind the general pitfalls of asynchronous programming in C# while implementing such task execution.

guest

Hello, so far I use Task.WhenAll to execute multiple tasks like in the example you have given, but I want to use Parallel.ForeachAsync.

I have seen MaxDegreeOfParallelism you have set it to 3. is that because _employeeIds contains 3? If I had 20, would I have to put 20?

Chayan

The default MaxDegreeOfParallelism for the Parallel.ForEachAsync is equal to the Environment.ProcessorCount, and for all other Parallel methods(For and ForEach) it is equal to -1, which means unlimited parallelism.

The optimal value for the MaxDegreeOfParallelism for CPU-bound operations is Environment.ProcessorCount, although oversubscription might help if the workload is unbalanced.

The Parallel.ForEachAsync is used typically for I/O-bound asynchronous operations, where the sweet spot depends on the capabilities of the remote server or the bandwidth of the network. So in this case there is no rule of thumb, you will have to start with a number and fine-tune it depending on performance.

In this example, we have set the value to 3 simply as we wanted to make at max 3 parallel calls. So you can set it to 20 if your remote service and network can support such concurrent requests. But please also remember, when the CPU has to switch from one thread to another (context switch) it has a cost, so if you use too many threads and the CPU is switching all the time, you decrease the performance.

I am using it in a .NET MAUI application, where I always get a list of 20 elements, I am making a call to the google API. Thanks for the explanation. I don’t know what the correct value would be…

Dennis

Thank you for the extensive post and benchmarking. While I would write some of the code differently, I appreciate your work and different opinions! Justing starting out as a blogger, I recently posted an in-depth article on best practices in async-await in C#. Maybe you might want to have a go. Cheers,

wpdiscuz

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

This browser is no longer supported.

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

Controller action return types in ASP.NET Core web API

  • 10 contributors

This isn't the latest version of this article. For the current release, see the .NET 8 version of this article .

This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 8 version of this article .

View or download sample code ( how to download )

ASP.NET Core provides the following options for web API controller action return types:

Specific type

  • IActionResult
  • ActionResult<T>
  • HttpResults

This article explains when it's most appropriate to use each return type.

The most basic action returns a primitive or complex data type, for example, string or a custom object. Consider the following action, which returns a collection of custom Product objects:

Without known conditions to safeguard against, returning a specific type could suffice. The preceding action accepts no parameters, so parameter constraints validation isn't needed.

When multiple return types are possible, it's common to mix an ActionResult return type with the primitive or complex return type. Either IActionResult or ActionResult<T> are necessary to accommodate this type of action. Several samples of multiple return types are provided in this article.

Return IEnumerable<T> or IAsyncEnumerable<T>

See Return IEnumerable<T> or IAsyncEnumerable<T> for performance considerations.

ASP.NET Core buffers the result of actions that return IEnumerable<T> before writing them to the response. Consider declaring the action signature's return type as IAsyncEnumerable<T> to guarantee asynchronous iteration. Ultimately, the iteration mode is based on the underlying concrete type being returned and the selected formatter affects how the result is processed:

  • When using System.Text.Json formatter, MVC relies on the support that System.Text.Json added to stream the result.
  • When using Newtonsoft.Json or with XML-based formatters the result is buffered.

Consider the following action, which returns sale-priced product records as IEnumerable<Product> :

The IAsyncEnumerable<Product> equivalent of the preceding action is:

IActionResult type

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type. Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200). Alternatively, convenience methods in the ControllerBase class can be used to return ActionResult types from an action. For example, return BadRequest(); is a shorthand form of return new BadRequestResult(); .

Because there are multiple return types and paths in this type of action, liberal use of the [ProducesResponseType] attribute is necessary. This attribute produces more descriptive response details for web API help pages generated by tools like Swagger . [ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action.

Synchronous action

Consider the following synchronous action in which there are two possible return types:

In the preceding action:

  • A 404 status code is returned when the product represented by id doesn't exist in the underlying data store. The NotFound convenience method is invoked as shorthand for return new NotFoundResult(); .
  • A 200 status code is returned with the Product object when the product does exist. The Ok convenience method is invoked as shorthand for return new OkObjectResult(product); .

Asynchronous action

Consider the following asynchronous action in which there are two possible return types:

  • A 400 status code is returned when the product description contains "XYZ Widget". The BadRequest convenience method is invoked as shorthand for return new BadRequestResult(); .

A 201 status code is generated by the CreatedAtAction convenience method when a product is created. The following code is an alternative to calling CreatedAtAction :

In the preceding code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

For example, the following model indicates that requests must include the Name and Description properties. Failure to provide Name and Description in the request causes model validation to fail.

If the [ApiController] attribute is applied, model validation errors result in a 400 status code. For more information, see Automatic HTTP 400 responses .

ActionResult vs IActionResult

The following section compares ActionResult to IActionResult

ActionResult<T> type

ASP.NET Core includes the ActionResult<T> return type for web API controller actions. It enables returning a type deriving from ActionResult or return a specific type . ActionResult<T> offers the following benefits over the IActionResult type :

  • The [ProducesResponseType] attribute's Type property can be excluded. For example, [ProducesResponseType(200, Type = typeof(Product))] is simplified to [ProducesResponseType(200)] . The action's expected return type is inferred from the T in ActionResult<T> .
  • Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T> . T converts to ObjectResult , which means return new ObjectResult(T); is simplified to return T; .

C# doesn't support implicit cast operators on interfaces. Consequently, conversion of the interface to a concrete type is necessary to use ActionResult<T> . For example, use of IEnumerable in the following example doesn't work:

One option to fix the preceding code is to return _repository.GetProducts().ToList(); .

Most actions have a specific return type. Unexpected conditions can occur during action execution, in which case the specific type isn't returned. For example, an action's input parameter may fail model validation. In such a case, it's common to return the appropriate ActionResult type instead of the specific type.

Consider a synchronous action in which there are two possible return types:

  • A 404 status code is returned when the product doesn't exist in the database.
  • A 200 status code is returned with the corresponding Product object when the product does exist.

Consider an asynchronous action in which there are two possible return types:

  • The [ApiController] attribute has been applied and model validation fails.
  • The product description contains "XYZ Widget".
  • A 201 status code is generated by the CreatedAtAction method when a product is created. In this code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

HttpResults type

In addition to the MVC-specific built-in result types ( IActionResult and ActionResult<T> ), ASP.NET Core includes the HttpResults types that can be used in both Minimal APIs and Web API.

Different than the MVC-specific result types, the HttpResults :

Are a results implementation that is processed by a call to IResult.ExecuteAsync .

Does not leverage the configured Formatters . Not leveraging the configured formatters means:

  • Some features like Content negotiation aren't available.
  • The produced Content-Type is decided by the HttpResults implementation.

The HttpResults can be useful when sharing code between Minimal APIs and Web API.

IResult type

The Microsoft.AspNetCore.Http.HttpResults namespace contains classes that implement the IResult interface. The IResult interface defines a contract that represents the result of an HTTP endpoint. The static Results class is used to create varying IResult objects that represent different types of responses.

The Built-in results table shows the common result helpers.

Consider the following code:

  • A 200 status code is returned with the corresponding Product object when the product does exist, generated by the Results.Ok<T>() .
  • A 201 status code is generated by the Results.Create method when a product is created. In this code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

Results<TResult1, TResultN> type

The static TypedResults class returns the concrete IResult implementation that allows using IResult as return type. The usage of the concrete IResult implementation offers the following benefit over the IResult type :

  • All the [ProducesResponseType] attributes can be excluded, since the HttpResult implementation contributes automatically to the endpoint metadata.

When multiple IResult return types are needed, returning Results<TResult1, TResultN> is preferred over returning IResult . Returning Results<TResult1, TResultN> is preferred because generic union types automatically retain the endpoint metadata.

The Results<TResult1, TResultN> union types implement implicit cast operators so that the compiler can automatically convert the types specified in the generic arguments to an instance of the union type. This has the added benefit of providing compile-time checking that a route handler actually only returns the results that it declares it does. Attempting to return a type that isn’t declared as one of the generic arguments to Results<> results in a compilation error.

  • A 200 status code is returned with the corresponding Product object when the product does exist, generated by the TypedResults.Ok<T> .
  • The [ApiController] attribute was applied and model validation fails.
  • A 201 status code is generated by the TypedResults.Created method when a product is created. In this code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

Additional resources

  • Handle requests with controllers in ASP.NET Core MVC
  • Model validation in ASP.NET Core MVC
  • ASP.NET Core web API documentation with Swagger / OpenAPI
  • A 201 status code is generated by the TypedResults.Create method when a product is created. In this code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

ASP.NET Core offers the following options for web API controller action return types:

This document explains when it's most appropriate to use each return type.

The simplest action returns a primitive or complex data type (for example, string or a custom object type). Consider the following action, which returns a collection of custom Product objects:

Without known conditions to safeguard against during action execution, returning a specific type could suffice. The preceding action accepts no parameters, so parameter constraints validation isn't needed.

When multiple return types are possible, it's common to mix an ActionResult return type with the primitive or complex return type. Either IActionResult or ActionResult<T> are necessary to accommodate this type of action. Several samples of multiple return types are provided in this document.

ASP.NET Core buffers the result of actions that return IEnumerable<T> before writing them to the response. Consider declaring the action signature's return type as IAsyncEnumerable<T> to guarantee asynchronous iteration. Ultimately, the iteration mode is based on the underlying concrete type being returned. MVC automatically buffers any concrete type that implements IAsyncEnumerable<T> .

  • A 201 status code is generated by the CreatedAtAction convenience method when a product is created. An alternative to calling CreatedAtAction is return new CreatedAtActionResult(nameof(GetById), "Products", new { id = product.Id }, product); . In this code path, the Product object is provided in the response body. A Location response header containing the newly created product's URL is provided.

ASP.NET Core includes the ActionResult<T> return type for web API controller actions. It enables you to return a type deriving from ActionResult or return a specific type . ActionResult<T> offers the following benefits over the IActionResult type :

  • The [ProducesResponseType] attribute's Type property can be excluded. For example, [ProducesResponseType(200, Type = typeof(Product))] is simplified to [ProducesResponseType(200)] . The action's expected return type is instead inferred from the T in ActionResult<T> .

ASP.NET Core

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

IMAGES

  1. 43 Free Task List Templates in Word Excel PDF

    task list result

  2. Task List Examples

    task list result

  3. Free Downloadable Task List Template + 10 Tips to Manage Your Tasks

    task list result

  4. 7 Free To Do Task List Templates

    task list result

  5. EXCEL of Simple Business Task List.xlsx

    task list result

  6. Task List Template

    task list result

VIDEO

  1. Number कितने ? / Cutt Off / 2nd List / Navodaya Result / 2024

  2. Task 1 result + Task 2 || Survival Show || ♡TIAXTHETIC♡

  3. How To Edit Task List On Notion

  4. Gamify Your Task List! #mindset #productivity #motivation

  5. 43. Delete Task in Todo List in Hindi

  6. Manage all your tasks in one place

COMMENTS

  1. How do I get the result or return value of a Task?

    To return a result from a Task you need to define the Task as such: Task<TResult> and pass the return type of the result as a generic parameter. (Otherwise the Task will return nothing) For Example: // Return a value type with a lambda expression Task<int> task1 = Task<int>.Factory.StartNew(() => 1); int i = task1.Result; // Return a named reference type with a multi-line statement lambda.

  2. Task<TResult>.Result Property (System.Threading.Tasks)

    If a directory contains no files, it simply calls the FromResult method to create a task whose Task<TResult>.Result property is zero (0). When the tasks finish, the total number of bytes in all a directory's files is available from the Result property. using System.Collections.Generic; using System.IO;

  3. How to Return a Value from 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 ...

  4. How to: Return a Value from a Task

    The Result property blocks the calling thread until the task finishes. To see how to pass the result of a System.Threading.Tasks.Task<TResult> class to a continuation task, see Chaining Tasks by Using Continuation Tasks. See also. Task-based Asynchronous Programming; Lambda Expressions in PLINQ and TPL

  5. c#

    Change your taskList to List<Task<SettingModel>> and also don't use task.Result to avoid Deadlock. Your code should be something like this: taskList.Add(GetSetting(key)); Since all tasks are awaited in await Task.WhenAll in OP's case, .Result wouldn't cause deadlock.

  6. Get the result of multiple tasks in a ValueTuple and WhenAll

    In .NET, you can use Task.WhenAll to wait for multiple tasks. Once the tasks are completed, you can get the results using .Result or by awaiting them. Task<int> task1 = Task.Run(() => 1); Task<string> task2 = Task.Run(() => "meziantou"); await Task.WhenAll(task1, task2); var task1Result = task1.Result; // or await task1 var task2Result = task2.Result; // or await task2 I don't really want ...

  7. Task.FromResult<TResult>(TResult) Method (System.Threading.Tasks

    Remarks. This method creates a Task<TResult> object whose Task<TResult>.Result property is result and whose Status property is RanToCompletion. The method is commonly used when the return value of a task is immediately known without executing a longer code path. The example provides an illustration.

  8. Task.CompletedTask, Task.FromResult and Return in C#

    The Task.FromResult is a sibling to Task.CompletedTask. It is a useful method in async programming to create a completed Task with a specific result. It also allows us to quickly return a completed Task in situations where we don't have asynchronous operations. Let's create the UseTaskFromResultAsync() method to understand this:

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

    Next, in order to check whether the task is completed, faulted, or canceled, we are going to use the following three properties of the Task class. IsCompleted { get; }: It returns true if the task has been completed; otherwise false. IsCanceled { get; }: It returns true if the task has been completed due to being canceled; otherwise false.

  10. C#

    Return a completed task with a result. I previously made a post on how to do this here. In short you can use Task.FromResult() to create a completed Task with a result of your choice. Below is an example: var completedTask = Task.FromResult<string>("SomeResult"); You can either await the above (preferred) or use .Result to get the string ...

  11. batch

    1. You should develop your batch step by step, starting in an open cmd window. ... by filtering with a findstr or with an if. for /f uses by default space/tab as delimiters and only token=1. tasklist /FI "IMAGENAME eq chrome.exe" ^| findstr /ic:"chrome.exe". Returns the bar PID numbers you are after.

  12. Task<TResult> Class (System.Threading.Tasks)

    Remarks. The Task<TResult> class represents a single operation that returns a value and that usually executes asynchronously. Task<TResult> objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task<TResult> object typically executes asynchronously on a thread pool thread rather than ...

  13. How to Execute Multiple Tasks Asynchronously in C#

    We get back the consolidated result. Let's now see if we can improve the performance of this functionality. Execute Multiple Tasks in Parallel using Task.WhenAll. Since the tasks for fetching employee details, salary and rating are independent of each other, it is easy to execute them in parallel to improve the overall performance of the ...

  14. How to check scheduled tasks in Windows

    How to view scheduled tasks in PowerShell. To see scheduled tasks on your Windows computer, open PowerShell as an admin and run this command: Get-ScheduledTask. To filter the results and only get the running scheduled tasks, you can use the command: get-scheduledtask | where state -eq "Running".

  15. How To Use Task Lists in Project Management

    To make a task list for your team, follow these steps: 1. Consider the project's size. The size of your project may affect the structure of your task list. For more intensive projects, you may want a more detailed task list. Consider how many tasks the project may have and the number of professionals the project manager has assigned to complete ...

  16. Task.Run Method (System.Threading.Tasks)

    The Run (Action, CancellationToken) method is a simpler alternative to the TaskFactory.StartNew (Action, CancellationToken) method. It creates a task with the following default values: Its CreationOptions property value is TaskCreationOptions.DenyChildAttach. It uses the default task scheduler.

  17. Task.WhenAll Method (System.Threading.Tasks)

    Examples. The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a List<Task> collection that is converted to an array and passed to the WhenAll(IEnumerable<Task>) method. After the call to the Wait method ensures that all threads have completed, the example examines the Task.Status property to determine whether any tasks have faulted.

  18. Why should I return Task<IActionResult> in a Controller?

    Async operations return a Task(it is not the result, but a promise made that will have the results once the task is completed. The async methods should be awaited so that it waits till the task is completed. if you await an async method, the return values won't be a task anymore and will be the results you expected. Imagine this async method:

  19. Controller action return types in ASP.NET Core web API

    In addition to the MVC-specific built-in result types (IActionResult and ActionResult<T>), ASP.NET Core includes the HttpResults types that can be used in both Minimal APIs and Web API. Different than the MVC-specific result types, the HttpResults: Are a results implementation that is processed by a call to IResult.ExecuteAsync.