Using the ValueTask of T object in C# 7.0

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:

System threading tasks extensions library in NuGet for ValueTask object

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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Using the ValueTask of T object in C# 7.0

  1. Geoff Hirst says:

    Nice one chap. Another gem for the toolbox. Are there any other good ones to be aware of in this Tasks.Extensions package?

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.