Dot Net Tutorials

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

Task in C# with Examples

In this article, I am going to discuss Task in C# with Examples. Please read our previous article where we discussed how to implement Asynchronous Programming using Async and Await Operators in C# with Examples.

In C#, when we have an asynchronous method, in general, we want to return one of the following data types.

  • Task and Task<T>
  • ValueTask and ValueTask<T>

We will talk about ValueTask later, Now let us keep the focus on Task. The Task data type represents an asynchronous operation. A task is basically a “promise” that the operation to be performed will not necessarily be completed immediately, but that it will be completed in the future.

What is the difference between Task and Task<T> in C#?

Although we use both of them i.e. Task and Task<T> in C# for the return data type of an asynchronous method, the difference is that the Task is for methods that do not return a value while the Task<T> is for methods that do return a value of type T where T can be of any data type, such as a string, an integer, and a class, etc. We know from basic C# that a method that does not return a value is marked with a void. This is something to avoid in asynchronous methods. So, don’t use async void except for event handlers.

Example to Understand Task in C#:

In our previous example, we have written the following SomeMethod.

Now, what we will do is we will move the Task.Dealy to separate method and call that method inside the SomeMethod. So, let’s create a method with the name Wait as follows. Here, we mark the method as async so it is an asynchronous method that will not block the currently executing thread. And when calling this method it will wait for 10 seconds. And more importantly, here we use the return type as Task as this method is not going to return anything.

In asynchronous programming when your method does not return anything, then instead of using void you can use Task. Now, from the SomeMethod we need to call the Wait method. If we call the Wait method like the below then we will get a warning.

Here, you can see green lines under the Wait method as shown in the below image.

Task in C# with Examples

Why is that?

This is because the Wait method returns a Task and because it does return a Task, then it means that this will be a promise. So, this warning of the Wait method informed us that, if we don’t use the await operator while calling the Wait method, the Wait method is not going to wait for this operation to finish, which means that once we call the Wait method, the next line of code inside the SomeMethod is going to be executed immediately. Let us see that practically. The following is the complete example code.

Output: Once you execute the above code, then you will observe that without any delay we are getting the output as shown in the below image. This is because we are not using the await operator while calling the Wait method and hence it will not wait for the Wait method to complete. After 10 seconds the print statement within the Wait method is printed.

What is the difference between Task and Task<T> in C#?

In the above example, we use await Task.Delay inside the Wait method. This will suspend the thread for this Wait method execution only. It will not suspend the thread for SomeMethod execution. Now, let’s see what happens when we use the await operator as shown in the below example.

First thing, once you put the await operator, as shown above, the green warning will be gone. With await operator we are saying, please wait for this Wait method execution to finish before executing the next line of code inside the SomeMethod. That means it will not execute the last print statement inside the SomeMethod until the Wait method completes its execution.

So, let us see that. The complete example code is given below

Now, you can observe in the above output that once it calls the Wait method, then the SomeMethod will wait for the Wait method to complete its execution. You can see that before printing the last print statement of the SomeMethod, it prints the printing statement of the Wait method. Hence, it proves that when we use await operator then the current method execution waits until the called async method completes its execution. Once the async method, in our example Wait method, complete its example, then the calling method, in our example SomeMethod, will continue its execution i.e. it will execute the statement which is present after the async method call.

What if you don’t want to wait for an asynchronous method in C#?

If you don’t want your method execution to wait for the asynchronous method to complete its execution, then, in that case, you need to use the return type of the asynchronous method to void. For a better understanding, please have a look at the below example. In the below example, we have used void as the return type of the asynchronous Wait method and while calling the asynchronous Wait method inside the SomeMethod we are not using await operator. This time please observe we are not getting any warning.

Now you can observe the first four statements are printed immediately without waiting for the Wait method. After 10 seconds only the last statement is printed on the console window. Now, I hope you understand when to use Task and when to use void as the return type of an asynchronous method. I hope you also understand the importance of await operator.

Here, we have seen the examples of the async method without returning any value and hence we can use either void or Task as per our requirement. But what if the async method returns a value? If the async method returns a value then we need to use Task<T> and which we will discuss in our next article.

In the next article, I am going to discuss How to Return a Value from a Task in C# with Examples. Here, in this article, I try to explain Task in C# with Examples. I hope you enjoy this Task C# with Examples 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.

7 thoughts on “Task in C#”

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

what is the difference of async and Task

Simply Awesome. Very nice explanation…I am looking for more content in this site. Keep up doing good work.

Don’t show videos ads . It’s ruining the site. And it’s very irritating as well.

Thanks we take into this consideration and disable the video ads.

hi, thanks for this very good tutorial, truly a step by step and clear run through, i went over a good few articles and left more puzzled after each one, until I read yours. Exactly how code should be explained.

Leave a Reply Cancel reply

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

blog post image

Andrew Lock | .NET Escapades Andrew Lock

  • .NET Core 6
  • Source Code Dive

A deep-dive into the new Task.WaitAsync() API in .NET 6

In this post I look at how the new Task.WaitAsync() API is implemented in .NET 6, looking at the internal types used to implement it.

Adding a timeout or cancellation support to await Task

In my previous post , I showed how you could "cancel" an await Task call for a Task that didn't directly support cancellation by using the new WaitAsync() API in .NET 6.

I used WaitAsync() in that post to improve the code that waits for the IHostApplicationLifetime.ApplicationStarted event to fire. The final code I settled on is shown below:

In this post, I look at how the .NET 6 API Task.WaitAsync() is actually implemented.

Diving into the Task.WaitAsync implementation

For the rest of the post I'm going to walk through the implementation behind the API. There's not anything very surprising there, but I haven't looked much at the code behind Task and its kin, so it was interesting to see some of the details.

Task.WaitAsync() was introduced in this PR by Stephen Toub .

We'll start with the Task.WaitAsync methods :

These three methods all ultimately delegate to a different, private , WaitAsync overload (shown shortly) that takes a timeout in milliseconds. This timeout is calculated and validated in the ValidateTimeout method , shown below, which asserts that the timeout is in the allowed range, and converts it to a uint of milliseconds.

Now we come to the WaitAsync method that all the public APIs delegate too . I've annotated the method below:

Most of this method is checking whether we can take a fast-path and avoid the extra work involved in creating a CancellationPromise<T> , but if not, then we need to dive into it. Before we do, it's worth addressing the VoidTaskResult generic parameter used with the returned CancellationPromise<T> .

VoidTaskResult is an internal nested type of Task , which is used a little like the unit type in functional programming ; it indicates that you can ignore the T .

Using VoidTaskResult means more of the implementation of Task and Task<T> can be shared. In this case, the CancellationPromise<T> implementation is the same in both the Task.WaitAsync() implementation (shown above), and the generic versions of those methods exposed by Task<TR> . .

So with that out the way, let's look at the implementation of CancellationPromise<T> to see how the magic happens.

Under the hood of CancellationPromise<T>

There's quite a few types involved in CancellationPromise that you probably won't be familiar with unless you regularly browse the .NET source code, so we'll take this one slowly.

First of all, we have the type signature for the nested type CancellationPromise<T> :

There's a few things to note in the signature alone:

  • private protected —this modifier means that the CancellationPromise<T> type can only be accessed from classes that derive from Task , and are in the same assembly . Which means you can't use it directly in your user code.
  • Task<TResult> —the CancellationPromise<T> derives from Task<TResult> . For the most part it's a "normal" task, that can be cancelled, completed, or faulted just like any other Task .
  • ITaskCompletionAction —this is an internal interface that essentially allows you to register a lightweight action to take when a Task completes. This is similar to a standard continuation created with ContinueWith , except it is lower overhead . Again, this is internal , so you can't use it in your types. We'll look in more depth at this shortly.

We've looked at the signature, now let's look at it's private fields. The descriptions for these in the source cover it pretty well I think:

So we have 3 fields:

  • The original Task on which we called WaitAsync()
  • The cancellation token registration received when we registered with the CancellationToken . If the default cancellation token was used, this will be a "dummy" default instance.
  • The timer used to implement the timeout behaviour (if required).

Note that the _timer field is of type TimerQueueTimer . This is another internal implementation, this time it is part of the overall Timer implementation . We're going deep enough as it is in this post, so I'll only touch on how this is used briefly below. For now it's enough to know that it behaves similarly to a regular System.Threading.Timer .

So, the CancellationPromise<T> is a class that derives from Task<T> , maintains a reference to the original Task , a CancellationTokenRegistration , and a TimerQueueTimer .

The CancellationPromise constructor

Lets look at the constructor now. We'll take this in 4 bite-size chunks. First off, the arguments passed in from Task.WaitAsync() have some debug assertions applied, and then the original Task is stored in _task . Finally, the CancellationPromise<T> instance is registered as a completion action for the source Task (we'll come back to what this means shortly).

Next we have the timeout configuration. This creates a TimerQueueTimer and passes in a callback to be executed after millisecondsDelay (and does not execute periodically). A static lambda is used to avoid capturing state, which instead is passed as the second argument to the TimerQueueTimer . The callback tries to mark the CancellationPromise<T> as faulted by setting a TimeoutException() (remember that CancellationPromise<T> itself is a Task ), and then does some cleanup we'll see later.

Note also that flowExecutionContext is false , which avoids capturing and restoring the execution context for performance reasons. For more about execution context, see this post by Stephen Toub .

After configuring the timeout, the constructor configures the CancellationToken support. This similarly registers a callback to fire when the provided CancellationToken is cancelled. Note that again this uses UnsafeRegister() (instead of the normal Register() ) to avoid flowing the execution context into the callback.

Finally, the constructor does some house keeping. This accounts for the situation where the source Task completes while the constructor is executing , before the timeout and cancellation have been registered. Or if the timeout fires before the cancellation is registered. Without the following block, you could end up with leaking resources not being cleaned up

That's all the code in the constructor. Once constructed, the CancellationPromise<T> is returned from the WaitAsync() method as a Task (or a Task<T> ), and can be awaited just as any other Task . In the next section we'll see what happens when the source Task completes.

Implementing ITaskCompletionAction

In the constructor of CancellationPromise<T> we registered a completion action with the source Task (the one we called WaitAsync() on):

The object passed to AddCompletionAction() must implement ITaskCompletionAction (as CancellationPromise<T> does) ITaskCompletionAction interface is simple, consisting of a single method (which is invoked when the source Task completes) and a single property:

CancellationPromise<T> implements this method as shown below. It sets InvokeMayRunArbitraryCode to true (as all non-specialised scenarios do) and implements the Invoke() method, receiving the completed source Task as an argument.

The implementation essentially "copies" the status of the completed source Task into the CancellationPromise<T> task:

  • If the source Task was cancelled, it calls TrySetCancelled , re-using the exception dispatch information to "hide" the details of CancellationPromise<T>
  • If the source task was faulted, it calls TrySetException()
  • If the task completed, it calls TrySetResult

Note that whatever the status of the source Task , the TrySet* method may fail, if cancellation was requested or the timeout expired in the mean time. In those cases the bool variable is set to false , and we can skip calling Cleanup() (as the successful path will call it instead).

Now you've seen all three callbacks for the 3 possible outcomes of WaitAsync() . In each case, whether the task, timeout, or cancellation completes first, we have some cleanup to do.

Cleaning up

One of the things you can forget when working with CancellationToken s and timers, is to make sure you clean up after yourself. CancellationPromise<T> makes sure to do this by always calling Cleanup() . This does three things:

  • Dispose the CancellationTokenRegistration returned from CancellationToken.UnsafeRegister()
  • Close the ThreadQueueTimer (if it exists), which cleans up the underlying resources
  • Removes the callback from the source Task , so the ITaskCompletionAction.Invoke() method on CancellationPromise<T> won't be called.

Each of these methods is idempotent and thread-safe, so it's safe to call the Cleanup() method from multiple callbacks, which might happen if something fires when we're still running the CancellationPromise<T> constructor, for example.

One point to bear in mind is that even if a timeout occurs, or the cancellation token fires and the CancellationPromise<T> completes, the source Task will continue to execute in the background. The caller who executed source.WaitAsync() won't ever see the output of result of the Task , but if that Task has side effects, they will still occur.

And that's it! It took a while to go through it, but there's not actually much code involved in the implementation of WaitAsync() , and it's somewhat comparable to the "naive" approach you might have used in previous versions of .NET, but using some of .NET's internal types for performance reasons. I hope it was interesting!

In this post I took an in-depth look at the new Task.WaitAsync() method in .NET 6, exploring how it is implemented using internal types of the BCL. I showed that the Task returned from WaitAsync() is actually a CancellationPromise<T> instance, which derives from Task<T> , but which supports cancellation and timeouts directly. Finally, I walked through the implementation of CancellationPromise<T> , showing how it wraps the source Task .

Popular Tags

net task return

Stay up to the date with the latest posts!

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 Read the Request Body in ASP.NET Core Web API

Posted by Code Maze | Updated Date Jan 31, 2024 | 0

How To Read the Request Body in ASP.NET Core Web API

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!

ASP.NET Core offers a versatile request-response pipeline, allowing seamless customization and intervention. Managing incoming requests to read the request body in an ASP.NET Core Web API application is a common and crucial task. There are multiple methods and techniques available, each tailored to specific requirements. This comprehensive guide delves into various approaches, providing detailed insights into their usage and benefits.

So let’s dive into the details.

Reading Request Body in a Controller

Parsing the request body within our ASP.NET Core Web API controllers gives us the flexibility to manage incoming data. Whether we choose to read the body as a string or employ model binding for structured data, these methods provide us with the tools to seamlessly process incoming requests.

Become a patron at Patreon!

Reading as String

We can read the request body as a string in a controller action. ASP.NET Core offers the Request property within controller actions, granting access to the Request.Body . However, this body has a Stream type and is unreadable to us. To handle this stream data as text, we need to convert it into a string format:

Here, we access the request body by invoking an extension method called ReadAsStringAsync() . We’ll delve into the details shortly. Once we obtain the response from the extension method, we straightforwardly return it from our action for testing purposes.

ReadAsStringAsync() Extension Method

Rather than directly converting the stream data to a string within the controller action, we can implement an extension method. This approach allows us to use it in various scenarios. As we progress through this article, there will be a recurrent need to convert stream data to a string. Leveraging extension methods provides an efficient solution to implement once and employ multiple times.

Let’s implement the extension method:

We establish an extension method named ReadAsStringAsync() . This method enhances the functionalities of the Stream type, enabling us to seamlessly convert stream data into a string format. To achieve this, we create an instance of the StreamReader class. Utilizing the StreamReader class facilitates the reading of characters from a stream, be it a file or a network stream.

For a deeper understanding of StreamReader and StreamWriter, we recommend consulting our article C# Back to Basics – Files, StreamWriter and StreamReader .

Despite the numerous constructor options available, in our context, we provide two parameters for the StreamReader . First is the stream data representing our request body and the second parameter, leaveOpen . This parameter ensures that the stream remains open even after the StreamReader completes its operations and is disposed.

In the subsequent step, we invoke the ReadToEndAsync() method of the reader object, which yields the string representation of the stream data. 

Using EnableBuffering for Multiple Reads

What occurs if we attempt to read the request body once more or multiple times in the above scenario? 

Let’s check this:

Now, let’s make an API call to this action method and inspect the response through Swagger:

Read request as a string

Here, we send the string “CodeMaze” as the request payload. When we check the response, we see that the first read attempt is successful, but the second one is not what we expect.

In situations requiring multiple reads of the request body, enabling buffering is essential. To achieve this, we can utilize the EnableBuffering() method of the Request object:

Here, we invoke the Request.EnableBuffering() method, allowing the reading of the request body multiple times. Following that, we invoke the ReadAsStringAsync() method. To ensure the stream remains open for subsequent reads, we set the leaveOpen parameter to true. Just before the second attempt, we reset the position of the request body to zero.

With the latest modifications in place, let’s test the API with the same parameter:

First: CodeMaze, Second: CodeMaze

After invoking the EnableBuffering() method, we effectively retrieve the request body for all subsequent attempts.

Model Binding

ASP.NET Core allows automatic deserialization of the request body to a predefined model class. This approach simplifies the handling of structured data. To make use of this intriguing feature, we utilize the [FromBody] attribute within our action, preceding the model parameter:

Here, ASP.NET Core automatically maps the incoming request body to the PersonItemDto class. Then, within the action body, we have the ability to access and utilize the properties of the model.

We are free to design the PersonItemDto class and its properties to match our application’s needs precisely:

Let’s explore one more scenario before bidding farewell to this topic. Let’s say we want to send and read an extra salary parameter to our action method. To solve this, we can try to add additional salary parameter with the FromBody attribute:

Is this approach correct?

There are no compilation errors when we build the code. However, during the runtime, when our application attempts to execute, an InvalidOperationException occurs at the line app.MapControllers() in the Program.cs file:

In simple terms, this exception notifies us that the FromBody attribute is permitted only once in action method parameters. Hence, it is advisable to gather all parameters within a single request model parameter.

Using a Custom Middleware

Middleware provides a powerful way to intercept requests and responses globally within our ASP.NET Core application. We can create custom middleware to read the request body. We will not go into details of Middleware in this article, but if you need a refresher, visit our ASP.NET Core Middleware – Creating Flexible Application Flows article.

Let’s see how to create a custom middleware to read the request body:

Here, we create a custom middleware named RequestBodyMiddleware .

Let’s now implement the Invoke() method to access and read the request body:

We examine the request path to identify specific routes initially. After that, we seamlessly translate the request body stream into a raw string representation by calling our extension method ReadAsStringAsync() . Following this, numerous options are available for leveraging the request body. Examples include logging the result, appending it to the request header, or checking the request length, among other potential uses. After concluding our processing of the request body, we direct the request to the subsequent middleware by invoking the _next() delegate.

To utilize this middleware, it’s essential to incorporate it in the Program.cs file:

Avoid Reading Large Request Bodies

Handling large request bodies in a web application demands caution due to potential memory issues, performance degradation, and resource exhaustion. The time-consuming processing of large bodies may lead to slower response times and reduced overall application throughput. Concerns include the risk of denial-of-service (DoS) attacks through intentionally large bodies and increased network overhead. To address these challenges, some best practices include setting size constraints, incorporating streaming mechanisms, and deploying asynchronous processing to improve scalability.

Let’s revisit our custom middleware to inspect the analysis of the request payload:

Here, we establish a condition to verify if the request length exceeds a predefined maximum length value. If the condition is met, we halt the request pipeline and return a status code of Payload Too Large (413) .

Using Action Filters to Read the Request Body

Action filters in ASP.NET Core provide a way to run logic before or after controller action methods execute. This functionality empowers us to intercept incoming requests and establish a stopping point to inspect the request body.

To learn more about the action filters, please check out Implementing Action Filters in ASP.NET Core .

Let’s create a custom action filter:

In this scenario, we create a custom action filter called ReadRequestBodyActionFilter that implements the IActionFilter interface. Within this filter, we define the OnActionExecuting() method to handle our specific logic. Then, we examine the request path and extract the request body using the ReadAsStringAsync() extension method. Lastly, we append the request body to the request header using the key ReadRequestBodyActionFilter .

To utilize this action filter, it’s essential to register it in the Program.cs file:

Using a Custom Attribute to Read the Request Body

When it comes to intercepting incoming requests, custom attributes can be used in combination with action filters to modify the behavior of the request processing pipeline.

Let’s create a custom attribute to inspect and read the request body:

Here, we create a custom attribute called ReadRequestBodyAttribute that implements the IAsyncActionFilter interface. Then, we implement the OnActionExecutionAsync() method to read the request body. Once again, we create a StreamReader object and we access the request body as a string by calling the ReadToEndAsync() method. Finally, we append the request body to the request header using the key ReadRequestBodyAttribute .

We can now proceed to utilize our custom attribute. To do so, we need to apply it to our controller action:

Here, we apply our custom attribute ReadRequestBody to the controller action ReadFromAttribute() . Within the action, we inspect the request header ReadRequestBodyAttribute and assign its content to the action response.

In this article, we have explored various methods to answer how to read the request body in an ASP.NET Core Web API application. Retrieving the request body by reading in the controller actions offers simplicity and contro l for basic scenarios. This approach is the most commonly used in .Net Core Web API projects.

Custom middleware can be used when we want extensive global interception abilities . This can allow us to log the request body inside only one place of the Web API endpoints. Also, custom middleware allows easy manipulation of both requests and responses in one place.

Action filters are a good candidate to encapsulate logic, enhancing the clarity and focus of controller actions. By using action filters, we abstract the intricacies of handling the request body . This allows the controller action to maintain a cleaner and more dedicated focus on its primary purpose.

In the realm of reading request bodies, we leverage custom attributes for specialized, declarative handling . This empowers us with precise control over the processing of request bodies . The suitability of each approach depends on the specific requirements of our application, spanning from fundamental control to the demand for encapsulation and specialization.

guest

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

Stuart Skinner 'great' in return as Oilers force Game 7

Connor McDavid's third assist of the night finds Ryan Nugent-Hopkins for a point-blank Edmonton goal. (0:39)

net task return

After a week on the bench, Stuart Skinner returned to the net to help the Edmonton Oilers force a Game 7 in their second-round series against the Vancouver Canucks .

Last appearing in Game 3 after struggling to start the series, Skinner made 14 saves in the Oilers' 5-1 win in Game 6 at Rogers Place in Edmonton, Alberta.

Game 7 will be played Monday at Rogers Arena in Vancouver as the winner will face the Dallas Stars in the Western Conference finals starting Thursday at the American Airlines Center in Dallas.

"I think by doing what we did tonight, I think we just showed a lot of desperation," Skinner said on the ESPN broadcast. "Guys were blocking shots all over the place. I think both teams played great. You got to give a lot of credit to Vancouver, but you know Vancouver is going to come out really hard especially in their barn. I think we're going to have to match that and bring some more."

Averaging 3.80 goals per game during the playoffs while boasting a defensive structure that's been among the strongest when it comes to limiting shots on goals and scoring chances is the formula the Oilers have used to come within a game of the Western Conference finals.

Figuring out how the Oilers could mesh their defensive structure with the most consistent version of Skinner, however, was one of those challenges they were trying to solve in a series in which the first five games were decided by a goal.

Especially when the Oilers limited the Canucks to 19.3 shots per game in the first three games only to find themselves down in the series with Skinner posting a 4.63 goals-against average and a .790 save percentage through Game 3.

Saturday saw the connection between the Oilers' defensive structure and Skinner finally click.

The Oilers, who had limited teams to 24.91 scoring chances per 60, limited the Canucks to 18 scoring chances in 5-on-5 play. They also held the Canucks to just seven high-danger scoring chances and didn't allow any in the second period.

Combining that defensive consistency with Skinner allowing only one goal on 15 shots added to an evening that saw the Oilers burst through for five goals. It was the third time this postseason and the first time in the second round that the Oilers have scored more than five goals.

Oilers captain Connor McDavid , who finished with three points, told the Sportsnet broadcast after the game that although Skinner didn't face many shots he did "a great job" handling what McDavid considered to be dangerous chances.

"We never had a doubt," McDavid said. "He's a battler. He's always been a battler. Our team always responds and he's no different. He responded great and gave us a great performance."

His role in the Oilers' Game 6 win is the latest development in what has been another mercurial season for the second-year goaltender.

A year ago, Skinner was a rookie who emerged as the No. 1 goaltender for his hometown team. He helped the Oilers reach the second round only for them to be eliminated in six games by the eventual Stanley Cup champion Vegas Golden Knights .

Skinner was pulled over the final three games of the series, which led to an offseason filled with questions. Much like the Oilers themselves, Skinner had a difficult start to the season but found consistency once the club fired coach Jay Woodcroft and hired Kris Knoblauch.

In that time, Skinner solidified his place as the team's No. 1 goaltender -- which is what made his performances through the first three games so jarring. It led to him being pulled to start the third period in the Oilers' Game 3 loss, with Knoblauch turning to Calvin Pickard in Games 4 and 5.

Pickard stopped 19 shots in the Oilers' Game 4 victory while allowing three goals on 35 shots in their 3-2 loss in Game 5 to the Canucks.

Knoblauch said after Game 3 that Skinner would return to the lineup at some point, and that point was Saturday.

Now he and the Oilers are just a win away from the conference finals.

"I think obviously, to start off, I think Calvin was amazing when he got put in," Skinner said. "Definitely got the job done and kept us in it. An unbelievable teammate. For me, I was able to get a little bit of rest and just work on my game and feel good about it again. I was able to come out and do what I had to do."

  • ABC7 New York 24/7 Eyewitness News Stream Watch Now
  • THE LOOP | NYC Weather and Traffic Cams Watch Now

Gilgo Beach investigators return to murder suspect Rex Heuermann's home

WABC logo

MASSAPEQUA PARK, Long Island (WABC) -- Investigators with the Gilgo Beach Homicide Task Force returned to the Massapequa Park home of murder suspect Rex Heuermann.

The task force embarked on an extensive search at the home at 7 a.m. Monday.

Two white tents could be seen set up in the front yard while forensic crews were spotted assembling cardboard boxes near large blue plastic bins -- presumably for more evidence collection.

Heuermann has pleaded not guilty to killing four women whose bodies were found near one another in a marshy stretch close to Gilgo Beach .

The bodies of the Gilgo Beach Four -- Maureen Brainard-Barnes, Melissa Barthelemy, Megan Waterman and Amber Costello - were all found wrapped in burlap.

net task return

The renewed interest in Heuermann's home comes as investigators continue to try to solve the deaths of six other Gilgo victims.

Suffolk County District Attorney Ray Tierney would only say that as "new information comes in, it becomes necessary to take additional steps," and that the search is "part of the ongoing investigation with regard to both charged and uncharged crimes."

When Tierney was asked if anything new surfaced to prompt the search, he said that investigations evolve.

"New information comes in, and as that new information comes in, it becomes necessary to take additional steps, and that is what we are doing," Tierney said. "But as prosecutors, we speak through indictments, so up and until and if that happens, we will talk. As for right now, we are not going to say anything, other than its part of an ongoing investigation."

Prosecutors previously revealed they seized hundreds of electronic devices from Heuermann's Massapequa Park home and Manhattan office following his arrest last July.

He used the devices to search for the deceased victims and their family members; the status of the investigation; for software that would assist in wiping or erasing data from computers and other similar digital devices and purchase digital masking and forensic wiping tools, prosecutors said.

The home is still occupied by Heuermann's wife and children -- even after their attorney said it was rendered unlivable due to the destruction of the initial search.

Heuermann's attorney did not not have a comment Monday in response to the new search. He is next due in court on June 18.

ALSO READ | Exclusive: Former secretary of accused Gilgo Beach serial killer Rex Heuermann speaks out

net task return

* More Long Island news

* Send us a news tip

* Download the abc7NY app for breaking news alerts

* Follow us on YouTube

Submit a tip or story idea to Eyewitness News

Have a breaking news tip or an idea for a story we should cover? Send it to Eyewitness News using the form below. If attaching a video or photo, terms of use apply.

Related Topics

  • MASSAPEQUA PARK
  • NASSAU COUNTY
  • GILGO BEACH
  • REX HEUERMANN

Top Stories

net task return

2 drivers arrested after 1-year-old critically hurt in Brooklyn crash

  • 2 hours ago

net task return

Man dead, others injured after 'severe' turbulence on flight

net task return

NYPD officers hurt in crash responding to 13-year-old grazed by bullet

net task return

AccuWeather: Sunny and warmer

net task return

4 FDNY firefighters injured battling Bronx store fire

Scammers using text messaging to trick job seekers

Trump deletes video referencing 'Unified Reich' after backlash

Safety top of mind at local beaches ahead of Memorial Day weekend

U.S. flag

A .gov website belongs to an official government organization in the United States.

A lock ( ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites.

  • Guidelines and Guidance Library
  • Core Practices
  • Isolation Precautions Guideline
  • Disinfection and Sterilization Guideline
  • Environmental Infection Control Guidelines
  • Hand Hygiene Guidelines
  • Multidrug-resistant Organisms (MDRO) Management Guidelines
  • Catheter-Associated Urinary Tract Infections (CAUTI) Prevention Guideline
  • Tools and resources
  • Evaluating Environmental Cleaning

Infection Control Basics

  • Infection control prevents or stops the spread of infections in healthcare settings.
  • Healthcare workers can reduce the risk of healthcare-associated infections and protect themselves, patients and visitors by following CDC guidelines.

Germs are a part of everyday life. Germs live in our air, soil, water and in and on our bodies. Some germs are helpful, others are harmful.

An infection occurs when germs enter the body, increase in number and the body reacts. Only a small portion of germs can cause infection.

Terms to know

  • Sources : places where infectious agents (germs) live (e.g., sinks, surfaces, human skin). Sources are also called reservoirs.
  • Susceptible person: someone who is not vaccinated or otherwise immune. For example, a person with a weakened immune system who has a way for the germs to enter the body.
  • Transmission: a way germs move to the susceptible person. Germs depend on people, the environment and/or medical equipment to move in healthcare settings. Transmission is also called a pathway.
  • Colonization: when someone has germs on or in their body but does not have symptoms of an infection. Colonized people can still transmit the germs they carry.

For an infection to occur, germs must transmit to a person from a source, enter their body, invade tissues, multiply and cause a reaction.

How it works in healthcare settings

Sources can be:.

  • People such as patients, healthcare workers and visitors.
  • Dry surfaces in patient care areas such as bed rails, medical equipment, countertops and tables).
  • Wet surfaces, moist environments and biofilms (collections of microorganisms that stick to each other and surfaces in moist environments, like the insides of pipes).
  • Cooling towers, faucets and sinks, and equipment such as ventilators.
  • Indwelling medical devices such as catheters and IV lines.
  • Dust or decaying debris such as construction dust or wet materials from water leaks.

Transmission can happen through activities such as:

  • Physical contact, like when a healthcare provider touches medical equipment that has germs on it and then touches a patient before cleaning their hands.
  • Sprays and splashes when an infected person coughs or sneezes. This creates droplets containing the germs, and the droplets land on a person's eyes, nose or mouth.
  • Inhalation when infected patients cough or talk, or construction zones kick up dirt and dust containing germs, which another person breathes in.
  • Sharps injuries such as when someone is accidentally stuck with a used needle.

A person can become more susceptible to infection when:

  • They have underlying medical conditions such as diabetes, cancer or organ transplantation. These can decrease the immune system's ability to fight infection.
  • They take medications such as antibiotics, steroids and certain cancer fighting medications. These can decrease the body's ability to fight infection.
  • They receive treatments or procedures such as urinary catheters, tubes and surgery, which can provide additional ways for germs to enter the body.

Recommendations

Healthcare providers.

Healthcare providers can perform basic infection prevention measures to prevent infection.

There are 2 tiers of recommended precautions to prevent the spread of infections in healthcare settings:

  • Standard Precautions , used for all patient care.
  • Transmission-based Precautions , used for patients who may be infected or colonized with certain germs.

There are also transmission- and germ-specific guidelines providers can follow to prevent transmission and healthcare-associated infections from happening.

Learn more about how to protect yourself from infections in healthcare settings.

For healthcare providers and settings

  • Project Firstline : infection control education for all frontline healthcare workers.
  • Infection prevention, control and response resources for outbreak investigations, the infection control assessment and response (ICAR) tool and more.
  • Infection control specifically for surfaces and water management programs in healthcare settings.
  • Preventing multi-drug resistant organisms (MDROs).

Infection Control

CDC provides information on infection control and clinical safety to help reduce the risk of infections among healthcare workers, patients, and visitors.

For Everyone

Health care providers, public health.

Senua's Saga: Hellblade 2 review - a triumphant return to a challenging story

A worrier's tale.

I think it's fair to say Ninja Theory had quite a daunting task when it came to producing a sequel to 2017's Hellblade: Senua's Sacrifice. The original was rightly praised for its exploration of grief, trauma and mental illness, but how do you tell more of a story about a woman's struggles with psychosis without seeming repetitive or worse, exploitative? The answer, it turns out, is you make Hellblade 2 - a game that is nothing short of phenomenal.

As you may remember, Hellblade: Senua's Sacrifice concerns itself with Pictish warrior Senua, a woman living with psychosis as she struggles to come to terms with her mental illness, the stigma that separates her from her community, and the death of her lover Dillian at the hands of raiding Northmen. After an opening cinematic briefly outlining the above, Hellblade 2 picks up more or less where it left off. The Northmen have resumed their raids on Senua's people and she has vowed to stop them. Allowing herself to be captured by slavers, she plans to assault the Northmen's stronghold from within and put an end to the raids once and for all. Unfortunately for her the weather has different ideas, leaving Senua shipwrecked and defenceless in a hostile, foreign land. Bound by her vow, she has no choice but to push on.

This is a game about keeping a promise, in other words. Senua has assumed responsibility for a whole community of people - something that both weighs on her as a character and also shifts the narrative focus away from her slightly. Whereas Senua's Sacrifice is firmly set around Senua and the various traumatic events she's trying to process, Hellblade 2 is much more about the people she meets: those she saves and those she can't, those she trusts and those she fears, and how she navigates those relationships. It's less a game about somebody battling mental illness and more about somebody who happens to have a mental condition going on a great and dangerous journey.

The outward-facing focus of Hellblade 2 is deeply satisfying from a character perspective. While Senua's psychosis is still very much something with which she struggles, she has a markedly different relationship with it after her first outing. Senua not only has more faith in her abilities, she's more compassionate towards herself than we've seen before, indicating that her psychosis is something she's managing, not battling. This is especially evident in her relationship with the Furies - aural manifestations of her condition that essentially provide commentary on what she's doing throughout the game. These voices overlap with one another, speaking in staccato bursts of fear and hope and encouragement and scathing, bitter criticism. While they're certainly not benevolent - listening to them is kind of like an ASMR scenario in which everybody secretly hates you - they do, at least, have more faith in Senua. They encourage her far more than they used to and even go so far as to stick up for her. When other voices drift into Senua's mind - her deceased, abusive father chief among them - the furies side with their host more often than not, urging her not to listen and to remember her strength. It's a rewarding sense of progress, especially considering how hard Senua had to fight to get there.

From a structural perspective, the core experience of Hellblade 2 is largely unchanged from the first. Senua's world is a series of puzzles, many of which hinge on tricks of perspective, interspersed by abrupt combat encounters and intense periods of hallucination. The puzzles are, for the most part, periods of calm and reflection - in some, Senua needs to walk around and line up certain elements in the world around her to make the shape of certain runes. In others, she finds herself in areas that are mirrored on the ceiling, requiring her to swap between these two spaces in order to make headway. They're not overly challenging, but still provide a sense of satisfaction when the solution becomes clear.

Hellblade 2 screenshot showing Senua on a shoreline with spectral figures cowering in the surf

As in the first, combat encounters are all about timing. Learning to dodge and parry attacks at the right moment is key, with perfectly timed blocks filling up a gauge that allows you to slow time and deal a flurry of attacks to your adversary. It's fairly forgiving - Senua can tank a surprising amount of damage and the game is quick to get you back into the fight on the rare occasions you do actually fall. That said, I found myself taking a lot more hits than I would have liked throughout the game, especially with some of the faster enemy types that are hard to read. These enemies fight differently as the game goes on, which keeps you on your toes and, without giving any of the story away, some of them are absolutely horrific.

The hallucinations into which Senua sometimes drifts are both intensely vivid and skillfully introduced. Oftentimes you won't realise Senua's sense of reality has become distorted until she's already some way into it, at which point the world around her shifts and warps, pressing in on her and realising some of her greatest fears. These hallucinations tend to happen during particularly emotive story beats, advancing the action and reflecting Senua's conflicted mental state. It's deft storytelling, for one thing, but it also ensures Hellblade 2 isn't torturing Senua for the sake of it. With the caveat that I have never experienced psychosis myself, the representation strikes me as thoughtful and grounded where it would be very easy to produce something garish and reductive.

Hellblade 2 screenshot showing Senua standing to one side, listening to two characters argue

There were, however, a couple of moments that made me wary, in which Senua is described as being chosen, or special, or as having powers from beyond the veil. Most of these comments come from the character Fargrímr, who is something of a mystic and, lest we forget, living in the 9th Century, but I was surprised to find one or two of them coming from the game's narrator. Chosen One narratives are certainly nothing new in video games or in fantasy, but using that framing around a character like Senua requires caution. This is a character who is strong in spite of her illness, not because of it and, while the moment was brief, I was surprised to see Hellblade 2 blurring that line even a little.

That quibble aside, Hellblade 2 is a superb game from a team that clearly knows what made the first one special. To say that the core experience is familiar, is not to say that it is simply more of the same - rather, it has both refined and expanded on the original on all fronts, creating a sequel that is nothing short of stunning.

Hellblade 2 screenshot showing Senua standing in front of a large, circular barrier made of interlocking sticks

For one thing, Hellblade 2 is absolutely gorgeous. The environments are rich, detailed and exquisitely lit - I genuinely struggle to think of another game in which the lighting is such a prominent and active part of the storytelling process. The character animations are smooth and believable, while the facial capture helps bring commanding performances from the likes of Melina Juergens, Chris O'Reilly and Aldís Amah Hamilton to life. I've also never felt compelled to mention lichen in a review before, but the moss and lichen studded throughout the game are both absolutely top notch.

Second, the combat is superb. It's responsive, allowing for feint attacks that throw off your enemies, and the animations absolutely shine throughout. Previously, groups of adversaries used to surround Senua and patiently wait their turn, which was functional if not necessarily exciting. Now, previously unseen combatants crash into view to replace the one you just dispatched - sometimes fleeing NPCs come with, getting cut down or tackling somebody out of the way. The camera responds to crushing blows and shifting tides with real weight, providing a sense of heft to battle that rivals even the best that God of War has to offer. In doing so, it wrests a good deal of camera control away from the player and, arguably, puts each set piece firmly on rails, but the payoff is electric.

Hellblade 2 screenshot showing Senua facing an enemy whose frame is fragmented and distorted

If there's one thing for which Senua's Sacrifice was especially well-praised it was the audio, and Ninja Theory has brought the same level of excellence to the sequel. The whispering of the furies flits from ear to ear like they're toying with you, while distorted booms and unsettling noises ring out from the darkness. The soundtrack features work from Heilung, a band whose pounding drums, throat singing and occasional snarls seem tailor made for the setting (the members of Heilung describe their music as 'amplified history', which is certainly fitting.) I'm loath to describe playing Hellblade 2 with headphones as a treat - at times it's downright uncomfortable - but it really is the best way to experience it.

Really my main takeaway from Hellblade 2 is that it pulls absolutely zero punches. The violence is brutal throughout and, at times, the game strays into fully-fledged horror. I consider myself to have a fairly strong constitution, but at a few points early in the game I found myself feeling genuinely queasy. There's also a section later on which could have come straight from Neil Marshall's 2005 film The Descent, which made me very unhappy indeed. The story goes to some extreme places both in terms of Senua's past and the relationships those around her are trying to manage, and her reactions to those extremes are genuine and heartfelt. With all of this wrapped up with an intricately designed soundscape, supremely fluid action and outstanding visuals, it's not only a grand production, but one that delivers its message with absolute power and verve..

In short, Hellblade 2 is as confident a sequel as any I've ever seen - Ninja Theory has shown tremendous ambition with this game and the result is equally tremendous. A lot has changed since the release of Senua's Sacrifice in 2017, not least in terms of our comfort and familiarity with mental health and mental illness as subject matter but, if there was any doubt as to whether Hellblade could move with the times, it can be safely put to rest now. Ninja Theory has not only proven it can read a changing landscape, but that Hellblade and Senua absolutely still deserve a place of prominence within that space.

A copy of Senua's Saga: Hellblade 2 was provided for review by Xbox Game Studios.

Read this next

  • Hellblade 2 developer Ninja Theory's next game reportedly already greenlit by Xbox
  • Lords of the Fallen joins Hellblade 2 on Xbox Game Pass this month
  • Hellblade 2 is only two weeks away, and fans feel Xbox should be making more noise

Review | Songs of Conquest review - fantasy tactics that favours breadth over depth

Review | Indika review - a dark, surreal, and devilishly playful drama

Review | 1000xResist review - a deeply personal exploration of diaspora politics and psychology

Review | Animal Well review - this one gets deep

Review | Hades 2 early access review - polish and terrifying power from some of the best out there

Digital Foundry | MSI MPG 321URX review: the best QD-OLED monitor for US buyers

Review | Sand Land review - a fitting tribute to a wonderful author

Review | No Rest For the Wicked early access review - a shaky start, but there's potential

Ross Lyon responds to Saints' criticism in wake of struggling AFL season

Sport Ross Lyon responds to Saints' criticism in wake of struggling AFL season

Ross Lyon points to a board during a break in an AFL match between St Kilda and Hawthorn.

St Kilda coach Ross Lyon concedes the criticism directed at him and his players is "valid", saying it is time for the group to respond with action on the field. 

The Saints slipped to 14th on the ladder following last week's shock five-point loss to lowly Hawthorn.

St Kilda great Nick Riewoldt took aim at Max King in the wake of the defeat, saying the Saints spearhead was "one-dimensional" and lacked "forward craft".

King has kicked 9.8 this season, while the Saints' average of 74 points per match ranks them 14th in the league.

"We've all got to work on stuff. Is it symptomatic [of the team's struggles]?" Lyon replied when asked about Riewoldt's comments on Thursday.

"Everyone's entitled to their opinion. Unless you're in the four walls — they're the only real opinions that count, to be honest."

Max King kicking during a 2024 AFL match.

Asked whether King needed to work on his forward craft, Lyon said: "I think everyone does.

"I remember Robert Walls, who was one of the great coaches, and Craig Bradley said to him when he went to Carlton, 'Keep coaching me, we all need to keep improving'."

The Saints' finals hopes now appear shot after losing four of their past five matches.

The defeat to Hawthorn was particularly hard to digest, given St Kilda entered the match as strong favourites.

"We were really disappointed. I knew there would be criticism," Lyon said ahead of Saturday night's match with Fremantle at Docklands.

"We were really disappointed with our offence.

"There were a lot of opportunities left on the table that we were really disappointed with.

"I accept the criticism because it's valid. I've said there was a sameness [about us].

"I'm not perturbed, but all there is [now] is action. Everyone does a lot of talking.

"We want to develop our young players, we want to get our senior players in good form. We've been spluttering.

"Ideally, we'd have another one or two wins on the board and I'd be pretty comfortable with all things taken into consideration."

  • X (formerly Twitter)
  • Australian Rules Football
  • gilgo beach

Gilgo Beach killer update: Investigators return to suspect's New York house

WABC logo

NEW YORK -- Investigators with the Gilgo Beach Homicide Task Force returned Monday to the Long Island home of murder suspect Rex Heuermann.

He has pleaded not guilty to killing four women whose bodies were found near one another in a marshy stretch close to Gilgo Beach .

The bodies of the Gilgo Beach Four -- Maureen Brainard-Barnes, Melissa Barthelemy, Megan Waterman and Amber Costello - were all found wrapped in burlap.

net task return

The Suffolk County District Attorney's office declined to comment other than to say the investigative work goes on.

SEE MORE: Gilgo Beach investigation: Police expand search area linked to man convicted of killing 2 women

"As District Attorney Tierney has previously stated, the work of the Gilgo Beach Homicide Task force is continuing," the statement said. "We do not comment on investigative steps while ongoing."

Prosecutors previously revealed they seized hundreds of electronic devices from Heuermann's Massapequa Park home and Manhattan office following his arrest.

He used the devices to search for the deceased victims and their family members; the status of the investigation; for software that would assist in wiping or erasing data from computers and other similar digital devices and purchase digital masking and forensic wiping tools, prosecutors said.

Heuermann is next due in court on June 18.

Related Topics

  • GILGO BEACH
  • REX HEUERMANN
  • U.S. & WORLD
  • INVESTIGATION

Gilgo Beach

net task return

Gilgo Beach murder suspect appears in court as evidence turned over

net task return

Gilgo Beach suspect's estranged wife giving him 'benefit of the doubt'

net task return

Suspected Gilgo Beach killer charged in 4th murder

net task return

Gilgo Beach serial killings cold case | Investigation timeline

Top stories.

net task return

3 people, 2 dogs rescued after small plane crash at Hooks Airport

  • 35 minutes ago

net task return

Suspect injured in shooting involving deputies in Porter: Officials

  • 2 hours ago

net task return

Updated CenterPoint map lets you check estimated day of restoration

net task return

Houston goes from oven to sauna as humidity increases this week

  • 28 minutes ago

net task return

'Black Twitter: A People's History' captures cultural phenomenon

  • 31 minutes ago

HISD adds 2 more schools to closures list due to A/C failures

More details expected in death of man crushed by crane during storm

FEMA help available for storm, flooding victims in some Texas counties

IMAGES

  1. CMPRO Fast Task: Return a Record to Initial Step with a Message

    net task return

  2. Return task start date

    net task return

  3. C# ThreadPool and Its Task Queue Explained (With Example)

    net task return

  4. How to Schedule Tasks in Windows 10 via Task Scheduler

    net task return

  5. Scenario 1 HTTP Timeout Example Using ETW Tracing and Netsh Commands

    net task return

  6. Managing Processes in .NET

    net task return

VIDEO

  1. B23 6BA Birmingham

  2. SnowRunner Safety Net 4K

  3. Точка входа в процедуру nextafterf не найдена в библиотеке DLL msvcr120_clr0400

  4. B23 6BA Birmingham

  5. B23 6BA Birmingham

  6. B23 6BA Birmingham

COMMENTS

  1. c#

    If your async method needs to return int you'd mark the return type of the method as Task<int> and you'll return plain int not the Task<int>. Compiler will convert the int to Task<int> for you. private async Task<int> MethodName() {. await SomethingAsync(); return 42;//Note we return int not Task<int> and that compiles.

  2. Async return types

    In this article. Async methods can have the following return types: Task, for an async method that performs an operation but returns no value.; Task<TResult>, for an async method that returns a value. void, for an event handler.; Any type that has an accessible GetAwaiter method. The object returned by the GetAwaiter method must implement the System.Runtime.CompilerServices ...

  3. How to Return a Value from Task in C#

    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.

  4. How to: Return a Value from a Task

    In this article. This example shows how to use the System.Threading.Tasks.Task<TResult> class to return a value from the Result property. To use this example, you must ensure that the C:\Users\Public\Pictures\Sample Pictures directory exists and that it contains files.. Example using System; using System.Linq; using System.Threading.Tasks; class Program { static void Main() { // Return a value ...

  5. c#

    I would like to return a string result from an async task. System.Threading.Tasks.Task.Run(async => await audatex.UploadInvoice(assessment, fileName)); public async Task UploadInvoice(string assessment, string fileName) { //Do stuff return string; } Async programming confuses me, can someone please explain it?

  6. Difference Between Returning and Awaiting a Task in C#

    Major Differences Between Returning and Awaiting a Task. To begin, let's consider a simple routine that returns plain Task: And its functional equivalent using async/await: This task simply emulates an operation running for a specific duration. It also throws an exception if the duration exceeds a certain limit.

  7. Generalized Async Return Types in C# 7

    Let us understand the Generalized Async Return Types (ValueTask) in C# 7 with an example. First of all, you need to add the System.Threading.Tasks.Extensions package from NuGet. Then modify the Program class code as follows. As you can see in the below example, instead of using Task<T>, now we are using ValueTask<T> which is a value type, not a ...

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

    The return keyword is used in a similar way in both synchronous and asynchronous methods to provide a value as the result of the method. Whether the method is synchronous or asynchronous, the basic purpose of the return keyword remains the same - to send a value back from the method to the calling code.. Conclusion. In this article, we learned the usage of Task.CompletedTask,Task.FromResult ...

  9. 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 ...

  10. Task in C# with Examples

    Task in C#. In C#, when we have an asynchronous method, in general, we want to return one of the following data types. Task and Task<T> ValueTask and ValueTask<T> We will talk about ValueTask later, Now let us keep the focus on Task. The Task data type represents an asynchronous operation.

  11. A deep-dive into the new Task.WaitAsync() API in .NET 6

    In this post I took an in-depth look at the new Task.WaitAsync () method in .NET 6, exploring how it is implemented using internal types of the BCL. I showed that the Task returned from WaitAsync () is actually a CancellationPromise<T> instance, which derives from Task<T>, but which supports cancellation and timeouts directly. Finally, I walked ...

  12. Advanced Tips for Using Task.Run With Async/Await

    In the previous guide in this series we saw why Task.Run is mainly useful for CPU-bound code. In exploring that topic it became clear that, although you can use Task.Run with other types of operations, it may not be the best use of system resources. We also saw how easy it is to await a call to Task.Run.But that's certainly not all there is to it.

  13. Getting a return value from a Task with C#

    Sometimes you want to get a return value from a Task as opposed to letting it run in the background and forgetting about it. You'll need to specify the return type as a type parameter to the Task object: a Task of T. .NET 4.0 Without specifying an input parameter: We count to 500 and…

  14. Task Class (System.Threading.Tasks)

    Creates a continuation that executes according to the specified continuation options and returns a value. Continue With<TResult> (Func<Task,TResult>, Task Scheduler) Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation uses a specified scheduler.

  15. Returning Boolean Task from a Task

    Return Bool (True or False) from Task Synchronously. Using Task<TResult> you can return boolean, int, or string depending on your requirements where the operand is TResult. Here declaration must specify a return type of Task<bool> or Task<int> as required. Async methods that don't contain a return statement usually have a return type of Task.

  16. How To Read the Request Body in ASP.NET Core Web API

    var requestBodySecond = await Request.Body.ReadAsStringAsync(); return Ok($"First: {requestBody}, Second:{requestBodySecond}"); } Now, let's make an API call to this action method and inspect the response through Swagger: Here, we send the string "CodeMaze" as the request payload.

  17. 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.

  18. Gymnastics Alyona Shchennikova Announces Return For Final Season

    BATON ROUGE - Alyona Shchennikova, a fifth-year senior from Evergreen, Colorado, has announced she will be returning to LSU Gymnastics for her final season of eligibility in 202

  19. Stuart Skinner 'great' in return as Oilers force Game 7

    After a week on the bench, Stuart Skinner returned to the net to help the Edmonton Oilers force a Game 7 in their second-round series against the Vancouver Canucks. Last appearing in Game 3 after ...

  20. Gilgo Beach serial killer: Task force investigators return to suspect

    MASSAPEQUA PARK, Long Island (WABC) -- Investigators with the Gilgo Beach Homicide Task Force returned to the Massapequa Park home of murder suspect Rex Heuermann. The task force embarked on an ...

  21. Australian volunteer doctor in Gaza 'stranded' after Israel's closure

    An Australian doctor reveals how he travelled to Gaza to volunteer but has become trapped in the war zone following Israel's seizure and closure of the Rafah border crossing.

  22. Western Bulldogs confirm Tom Liberatore's return plan, Beveridge candid

    In short: The Western Bulldogs have been given a morale boost ahead of facing top side Sydney on Thursday night, with premiership midfielder Tom Liberatore given a pathway to return to AFL. The ...

  23. Infection Control Basics

    Infection prevention, control and response resources for outbreak investigations, the infection control assessment and response (ICAR) tool and more. Infection control specifically for surfaces and water management programs in healthcare settings. Preventing multi-drug resistant organisms (MDROs). Sources. Infection control prevents or stops ...

  24. Senua's Saga: Hellblade 2 review

    After an opening cinematic briefly outlining the above, Hellblade 2 picks up more or less where it left off. The Northmen have resumed their raids on Senua's people and she has vowed to stop them ...

  25. What is the best way to return completed Task?

    5. Answer from Stephen Toub (MSFT): If you want a new Task object each time, Task.FromResult is the most efficient. Task.Delay (0) in its current implementation will return a cached task, but that's an implementation detail. If you want to use a cached task, you should cache one yourself, e.g. private static readonly Task s_completedTask = Task ...

  26. When Does 'Bridgerton' Season 3, Part 2 Come Out On ...

    Bridgerton Season 3, part one premiered on Thursday, May 16, 2024, at 3:00 a.m. ET or midnight PT. The second four episodes in part two will also drop on Netflix at the same time — 3:00 a.m. ET ...

  27. Ross Lyon responds to Saints' criticism in wake of struggling AFL

    The Saints play the Dockers on Saturday night. St Kilda coach Ross Lyon concedes the criticism directed at him and his players is "valid", saying it is time for the group to respond with action on ...

  28. Gilgo Beach murders: Investigators return to alleged serial killer Rex

    The Suffolk County District Attorney's office declined to comment other than to say the investigative work goes on. SEE MORE: Gilgo Beach investigation: Police expand search area linked to man ...

  29. How to return error from async funtion returning Task<T>

    @IgalS. note that using just an await as the last instruction of a method returning Task<T> is generally unneeded and will introduce some (not a lot, but some) performance costs. If you are not doing anything after your await (just returning the value), then just don't mark the method async and directly return your Task object so it's only awaited from the calling method.

  30. Proper way to implement methods that return Task<T>

    return await Task.Run(...); This leads to performance degradation due to additional instructions and allocations. So the rule of thumb is: if your method ends with await ... or return await ..., and it is the one and only await statement, then it's generally safe to remove the async keyword and directly return the Task that you were going to await.