Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created September 6, 2023 06:16
Show Gist options
  • Save admir-live/ef07bb71fa38bc6f9ff3ed9e53d19930 to your computer and use it in GitHub Desktop.
Save admir-live/ef07bb71fa38bc6f9ff3ed9e53d19930 to your computer and use it in GitHub Desktop.
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