Created
September 6, 2023 06:16
-
-
Save admir-live/ef07bb71fa38bc6f9ff3ed9e53d19930 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading.Tasks; | |
public class TaskExamples | |
{ | |
// Using Task when not awaiting and returning task-like result | |
public Task<string> GetStaticMessageTask() | |
{ | |
// Directly returning a completed task without the need for async keyword | |
return Task.FromResult("Hello, World!"); | |
} | |
// Using ValueTask when returning a value type or to avoid Task allocation overhead | |
public ValueTask<int> GetStaticNumberValueTask() | |
{ | |
// Directly returning a value using ValueTask without the need for async keyword | |
return new ValueTask<int>(42); | |
} | |
} | |
// Notes in comments: | |
// 1. Task.FromResult is a way to return a completed task with a given result. | |
// 2. ValueTask is a struct (value type), so it doesn't have the heap allocation overhead of Task (which is a class/reference type). | |
// 3. Using ValueTask can be beneficial when you want to minimize allocations, especially in high-performance scenarios. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment