If you observe System.IO.Stream
methods, for example, you will see that, synchronous methods Stream.Read()
and Stream.Write()
accept Span<byte>
and asynchronous methods Stream.ReadAsync()
and Stream.WriteAsync()
accept Memory<byte>
. So if you are using true asynchronous methods, you shouldn't need to create Span<>
.
In your case you don't need to wrap the result in Task
. The operation will complete synchronously and will be written in the Task
. So when you wrap it in Task
and await
it, you are literally saying "Wrap this result in task, and then give me the result of the task.".
But if you really want to return Task
from your method, you can remove the async
and await
keywords. The method will still be awaitable from outside. (Again: In this case there is no need to wrap the result in Task
)
// Removed async await
public static Task<bool> IsBase64StringAsync(string base64)
{
Span<byte> buffer = new Span<byte>(new byte[base64.Length]);
return Task.FromResult(Convert.TryFromBase64String(base64, buffer, out int bytesParsed));
}
// Synchronous method
public static bool IsBase64String(string base64)
{
Span<byte> buffer = new Span<byte>(new byte[base64.Length]);
return Convert.TryFromBase64String(base64, buffer, out int bytesParsed);
}