While Stephen's answer is correct... if you need to use a Span<T>
in an async
method and you can use C# 7 or above, then you can take advantage of a language feature called local functions to solve for the Parameters or locals of type 'T' cannot be declared in async methods or lambda expressions
error. Below is an example of how you could do that... and once again this is meant to solve for the reason given.
using System;
using System.Text;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
var base64Str = Convert.ToBase64String(Encoding.UTF8.GetBytes("this is a Base64 str"));
var notBase64Str = "this is not a Base64 str";
Console.WriteLine(await IsBase64String(base64Str)); // True
Console.WriteLine(await IsBase64String(notBase64Str)); // False
}
public static async Task<bool> IsBase64String(string base64)
{
return await Task.FromResult(CheckIfIsBase64String());
// Note the use of a local non-async function so you can use `Span<T>`
bool CheckIfIsBase64String()
{
// the use of stackalloc avoids array heap allocation
Span<byte> buffer = stackalloc byte[base64.Length];
return Convert.TryFromBase64String(base64, buffer, out int bytesParsed);
}
}
}
the code on dotnetfiddle.net