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
/Task
will not have separateThreadStatic
instance. So lock is necessary. - If above is true, only restriction in
lock
is thatawait
cannot be used inlock
. So it is safe to uselock
inasync function
. - (edit)
lock (r)
forr
instance, is it okay? Official document and other codes I looked created otherobject
for onlylock
.