You will be fine. Infection would require some bacteria to get into your body, from outside your body.
Normally bacteria get in your body either because you eat them, you breathe them in, or you cut yourself and they get through your skin. There are other less common routes (through the eyes, up the urethra) . A biopsy has a risk because your skin is punctured.
Masturbation has no risk as it is an outgoing process, nothing is going in your body only out.
You will be surprised (and terrified) by the colour. What comes out will be black, or very dark brown. Don't worry and have another go, it will be a week or two before what comes out is white.
There is a tiny argument for getting as much out as quickly as possible. The iron in the dead blood, can make future MRI scans harder to read, so better to get it out of your prostate. I doubt this is significant enough to justify excessive masturbation, but any excuse to masturbate is good enough for me.