Using the ValueTask of T object in C# 7.0
January 17, 2018 2 Comments
By now probably all .NET developers are aware of the await and async keywords, what they do and how they work.
Here’s a small example where the CalculateSum function simulates a potentially time-consuming mathematical operation:
public class AsyncValueTaskDemo { public void RunDemo() { int res = CalculateSum(0, 0).Result; Console.WriteLine(res); } private async Task<int> CalculateSum(int a, int b) { if (a == 0 && b == 0) { return 0; } return await Task.Run(() => a + b); } }
The if block in CalculateSum simulates the case where we want to avoid running the complex solution in a Task and instead return a simple integer. So if “a” and “b” are both 0 then we immediately want to return 0 and not continue with the awaited Task. The problem is that the above code will create a Task even if we do not hit the code with Task.Run. So if both a and b are 0 the function will still create a Task which in this case is an unnecessary operation.
C# 7.0 provides the generic ValueTask object for exactly this scenario. ValueTask is available in a NuGet package called System.Threading.Tasks.Extensions:
The solution only involves to return a ValueTask from the function instead of a Task:
public class AsyncValueTaskDemo { public void RunDemo() { int res = CalculateSum(0, 0).Result; Console.WriteLine(res); } private async ValueTask<int> CalculateSum(int a, int b) { if (a == 0 && b == 0) { return 0; } return await Task.Run(() => a + b); } }
View all various C# language feature related posts here.
Nice one chap. Another gem for the toolbox. Are there any other good ones to be aware of in this Tasks.Extensions package?
Hi Geoff, thanks for your comment, I’m not sure yet, I’ve only just started looking into it. //Andras