The program I am writing is a game server which will have multiple sessions in separate thread. To avoid unnecessary lock waiting time, [ThreadStatic] was added.
The program will include some async functions and
ThreadSafeStaticRNG(this class) will be used in async.
public class ThreadSafeStaticRNG
{
[ThreadStatic]
static Random r = new Random();
/// <summary>
/// get random number from [min,max)
/// </summary>
/// <returns></returns>
public static int GetNext(int min, int max)
{
int n;
lock (r)
{
n = r.Next(min, max);
}
return n;
}
}
I need verification for;
- As I understand, worker thread created with
async/Taskwill not have separateThreadStaticinstance. So lock is necessary. - If above is true, only restriction in
lockis thatawaitcannot be used inlock. So it is safe to uselockinasync function. - (edit)
lock (r)forrinstance, is it okay? Official document and other codes I looked created otherobjectfor onlylock.