See https://github.com/dotnet/runtime/pull/60335#issuecomment-942382490, it could simplify the code a lot.