C#: Initialize Random() only once in a singleton pattern - c#

I am trying to initialize only once a random variable, let's say 'rnd'. So If from many points of my program it is called, then the random variable will not be initialized again, only first time.
So I have created a singleton but I do not know how to call only once Random().
public sealed class Randomize
{
private static Randomize instance = null;
private static readonly object padlock = new object();
Randomize()
{
}
public static Randomize Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Randomize();
}
return instance;
}
}
}
}
Within this class I would like to create a private readonly random variable, 'rnd', which is initialized only once, the first time, to:
Random rnd = new Random()
Then, I would like to create a property to read its value, for example:
public Random Rnd
{
get { return rnd; }
}
I do not want to allow to change its value because it is assigned first time only, so I only want the property to be readonly (get), not set.
So from many points of my program I can do:
private readonly Random rnd;
Random rnd = Randomize.Instance.Rnd;
But each time I call it using above expression I do not want to initizalize random variable again (by doing new Random()) instead I want to always obtain the same value it was rnd variable was initialized for first time.
Any ideas on how to do it?

Just use a static constructor, by definition that is gaurenteed to only be called once
The MSDN Documentation States :
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
public sealed class Randomize
{
private static Randomize instance = null;
private static readonly object padlock = new object();
public Random GetRandom { get { return rnd; } }
private static readonly Random rnd;
static Randomize()
{
rnd = new Random();
}
}

You can access Randomize.Random with the following snippet and it will always return the once-initialized Random rnd field.
public sealed class Randomize {
private static readonly Random rnd = new Random();
public static Random Random {
get {
return rnd;
}
}
}

Read only variables can be assigned in the constructor, so I would go that route.
public sealed class Randomize {
/* access level here */ Random rnd { get { return r; } }
private readonly Random r;
static Randomize() {
r = new Random();
}
}
// or
private readonly Random r = new Random();
public Random rnd {
get {
return r;
}
}

Related

How to get some random numbers printing continually in the console?

My problem is that when I am trying to use Unity to spawn some objects at randomized locations, for some unknown reason, the location of those spawned objects is the same location.
I tried to add Thread.Sleep() to my code and the location will be randomized.
Here is an example:
class Program
{
static void Main(string[] args)
{
var mytest = new Program();
Console.WriteLine(mytest.test());
Thread.Sleep(500);
Console.WriteLine(mytest.test());
Thread.Sleep(500);
Console.WriteLine(mytest.test());
Thread.Sleep(500);
}
public int test()
{
Random random = new Random();
int testrandom = random.Next(5, 100);
return testrandom;
}
}
I don't want to use Thread.Sleep() all the time, is there a way to get past this problem?
While using debugging, I found that without using Thread.Sleep(), the local variable testrandom will be randomly updated as testrandom = 30,testrandom=32,testrandom=13..., but the result is different, the result is testrandom=30 and repeats itself 3 times. Can someone tell me why is this happening? Maybe it runs too fast?
.NET Random class is seeded by system clock if no explicit seed is given, so if you create new instances in short time apart from each other each instance will give you same number. This is also reason why adding sleep between calls to mytest.test() mitigates problem, as system clock has advanced by the time Thread.Sleep is over.
You should reuse same instance of Random, and use that instance every time:
class Program
{
private Random random = new Random();
static void Main(string[] args)
{
var mytest = new Program();
Console.WriteLine(mytest.test());
Console.WriteLine(mytest.test());
Console.WriteLine(mytest.test());
}
public int test()
{
int testrandom = random.Next(5, 100);
return testrandom;
}
}
Also, you can declare your test() method and Random instance as static, so you don't have to create instance of Program-class:
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
Console.WriteLine(test());
Console.WriteLine(test());
Console.WriteLine(test());
}
public static int test()
{
int testrandom = random.Next(5, 100);
return testrandom;
}
}

c# how to code a class method that can be called on the instance of the class

using c# .net 4.7.1 I have a class called Deck, here's the code:
public class Deck
{
public Card[] DeckOfCards { get; private set; } = new Card[56];
public Deck()
{
DeckOfCards = NewDeck();
}
private Card[] NewDeck()
{
Card[] newDeck = new Card[56];
....
return newDeck;
}
}
I would like to declare a class method within Deck called Shuffle that I would be able to call on the instance of Deck that I create. Here's how I picture my Main method in my program looking like:
class program
{
static void Main(string[] args)
{
Deck WorkingDeck = new Deck();
WorkingDeck.DeckOfCards.Shuffle();
....
}
}
Here's all I have for the class method Shuffle so far:
public Card[] Shuffle(this Card[] DeckToShuffle)
{
Random rnd = new Random();
Card[] ShuffledDeck = DeckToShuffle.OrderBy(x => rnd.Next()).ToArray();
return ShuffledDeck;
}
But this requires that I pass a Card[] in my method call. I would like the method to use WorkingDeck.DeckOfCards as the Deck that gets shuffled. Can someone point me in the right direction to be able to do this? Thanks in advance.
In this particular scenario, an Extension method would be a good solution.
public static class Extensions
{
public static void Shuffle(this IEnumerable<Card> source)
{
// Body of Shuffle
}
}
This would help you call shuffle as you desired
Deck WorkingDeck = new Deck();
WorkingDeck.DeckOfCards.Shuffle();
First, you can simplify your Deck class as follows:
public class Deck {
public Card[] DeckOfCards { get; private set; } = NewDeck();
private static Card[] NewDeck() {
Card[] newDeck = new Card[56];
....
return newDeck;
}
}
If you wish to make Shuffle change the order of cards in your Deck, you could write an extension method, like this:
static class DeckExtensions {
public static void Shuffle(this deck)
{
Random rnd = new Random();
deck.DeckOfCards = deck.DeckOfCards.OrderBy(x => rnd.Next()).ToArray();
}
}
The DeckOfCards property is a member of the class. A method on a class can automatically access its members (either implicitly or via the this keyword).
public class Deck
{
public Card[] DeckOfCards { get; private set; };
public Deck()
{
this.DeckOfCards = NewDeck();
}
static Card[] NewDeck()
{
Card[] newDeck = new Card[56];
....
return newDeck;
}
public void Shuffle()
{
Random rnd = new Random();
Card[] shuffledDeck = this.DeckOfCards.OrderBy(x => rnd.Next()).ToArray();
this.DeckOfCards = shuffledDeck;
}
}
You would invoke it like this:
static void Main(string[] args)
{
Deck workingDeck = new Deck();
workingDeck.Shuffle();
....
}
This design has Deck as a mutable object: Shuffle alters the order of the existing deck, rather than creates a different deck.
As an aside, there are better shuffling methods to use. The term to Google here is 'Fisher-Yates algorithm'.

C# Singleton pattern with triggerable initialization

I need a singleton that:
is lazy loaded
is thread safe
loads some values at construction
those values can be queried at any time
the initialization MAY happen at some precise time, before the querying begins - so I must be able to trigger it from the outside somehow. Of course, triggering multiple times should only do the initialization once.
I use .NET 3.5.
I've started with Jon Skeet's implementation (5th version) using a static subclass:
public sealed class Singleton
{
IEnumerable<string> Values {get; private set;}
private Singleton()
{
Values = new[]{"quick", "brown", "fox"};
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
This ticks almost all the boxes, except the "trigger initialization from outside". Since the actual initialization happens inside the ctor, it can't happen more than once.
How can this be accomplished?
The singleton will be used like this:
public static void Main(){
//do stuff, singleton should not yet be initialized.
//the time comes to initialize the singleton, e.g. a database connection is available
//this may be called 0 or more times, possibly on different threads
Singleton.Initialize();
Singleton.Initialize();
Singleton.Initialize();
//actual call to get retrieved values, should work
var retrieveVals = Singleton.Instance.Values;
}
Seems like you could do:
public sealed class Singleton
{
IEnumerable<string> Values {get; private set;}
private Singleton(bool loadDefaults)
{
if (loadDefaults)
Values = new[]{"quick", "brown", "fox"};
else
Values = new[]{"another", "set", "of", "values"};
}
public static Singleton Instance { get { return Nested.instance; } }
public static void Initialize() {
Nested.Initialize();
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton(true);
private static object instanceLock = new object();
private static bool isInitialized = false;
public static void Initialize() {
lock(instanceLock) {
if (!isInitialized) {
isInitialized = true;
instance = new Singleton(false);
}
}
}
}
}
Or to create a single instance that will be updated:
public sealed class Singleton
{
IEnumerable<string> Values {get; private set;}
private Singleton()
{
Values = new[]{"quick", "brown", "fox"};
}
public static Singleton Instance { get { return Nested.instance; } }
private static object instanceLock = new object();
private static bool isInitialized = false;
public static void Initialize() {
lock(instanceLock) {
if (!isInitialized) {
isInitialized = true;
Instance.Values = new[]{"another", "set", "of", "values"};
}
}
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
And the third variation based on your immutable comment and removal of Nested class comment:
public sealed class Singleton
{
IEnumerable<string> Values {get; private set;}
private Singleton()
{
Values = new[]{"quick", "brown", "fox"};
}
private static Singleton instance;
private static object instanceLock = new object();
public static Singleton Instance {
get {
Initialize();
return instance;
}
}
public static void Initialize() {
if (instance == null) {
lock(instanceLock) {
if (instance == null)
instance = new Singleton();
}
}
}
}
The first idea I had was to just use a throwaway variable assigned to the singleton's instance, which would (probably?) trigger the initialization
static Main()
{
var unused = Singleton.Instance;
//this should initialize the singleton, unless the compiler optimizes it out.
//I wonder if the compiler is smart enough to see this call has side effects.
var vals = Singleton.Instance.Values;
}
... but programming by side-effects is something I try hard to avoid, so let's make the intention a bit clearer.
public class Singleton {
public static void Initialize() {
//this accesses the static field of the inner class which triggers the private Singleton() ctor.
Instance._Initialize();
}
private void _Initialize()
{ //do nothing
}
[the rest as before]
}
so the usage would be:
static Main()
{
//still wondering if the compiler might optimize this call out
Singleton.Initialize();
var vals = Singleton.Instance.Values;
}
Btw this would also work:
static Main()
{
var vals = Singleton.Instance.Values;
}
Compiler optimization aside, I think this deals with all the requirements.
You can set up an Initialize method that can be fired from outside, if you need the initialize to happen later, but if the values are different on each time it is fired, then it cannot be static, which violates the Singleton pattern.
Based on your example, which has no variables, I assume you are just delaying when the initialization happens (routine rather than constructor), but your question suggests you want different values, but if multiple initializations happen close together, it only initializes once, so I am a bit confused on this.
I am not sure you need a Singleton only implmentation, but cannot fully answer without information on whether or not the Initialize() runs the same code every time or has some type of variable nature.
You can use double-checked locking pattern. Just add following code in you Singleton class:
public sealed class Singleton
{
..........................
private static object locker = new object();
private static bool initialized = false;
public static void Initialize() {
if (!initialized){
lock(locker) {
if (!initialized){
//write initialization logic here
initialized = true;
}
}
}
}
.......................
}
You can do something like this
public sealed class Singleton
{
IEnumerable<string> Values { get; set; }
private Singleton()
{
Console.WriteLine("-- Private Singleton constructor");
Values = new[] { "quick", "brown", "fox" };
}
public static Singleton Instance
{
get
{
Console.WriteLine("- Singleton Instance");
return Nested.instance;
}
}
public static void Initialize()
{
Console.WriteLine("- Singleton Initialize");
Nested.Initialize();
}
internal class Nested
{
private static object syncRoot = new object();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
Console.WriteLine("-- Static Nested constructor");
}
internal static readonly Singleton instance = new Singleton();
internal static void Initialize()
{
lock (syncRoot)
{
Console.WriteLine("-- Locked");
Console.WriteLine("--- Nested Initialize");
Console.WriteLine("-- Unlocked");
}
}
}
}
Usage
class Program
{
static void Main(string[] args)
{
var i = Singleton.Instance;
i = Singleton.Instance;
Console.WriteLine("-----");
Singleton.Initialize();
Singleton.Initialize();
Singleton.Initialize();
Console.Read();
}
}
Which outputs
- Singleton Instance
-- Private Singleton constructor
-- Static Nested constructor
- Singleton Instance
-----
- Singleton Initialize
-- Locked
--- Nested Initialize
-- Unlocked
- Singleton Initialize
-- Locked
--- Nested Initialize
-- Unlocked
- Singleton Initialize
-- Locked
--- Nested Initialize
-- Unlocked
public class Singleton<T> where T : class, new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
throw new Exception("singleton needs to be initialised before use");
}
return instance;
}
}
public static void Initialise(Action<T> initialisationAction)
{
lock(typeof(Singleton<T>))
{
if (instance != null)
{
return;
}
instance = new T();
initialisationAction(instance);
}
}
}

c# newb question from "Head Start C# Greyhound Lab"

i'm new at C # and i'm creating a racetrack simulator, but i'm currently encountering some issues when i run my code. I have an array of four Greyhound objects, and if I call Greyhound.Run on my form1.cs and i don't have a "MessageBox.Show("Distance" + distance)" on my Run method, which shows me how many pixels each greyhound is supposed to move, all of the greyhounds end up moving the same distance. I don't understand why this is happening
namespace Race
{
class Greyhound
{
public int StartingPosition;
public int RacetrackLength;
public PictureBox MyPictureBox = null;
public int Location = 0;
public Random Randomizer;
public bool Run()
{
Point p = MyPictureBox.Location;
if (p.X + MyPictureBox.Width >= RacetrackLength)
{
//TakeStartingPostion();
return true;
}
else
{
Randomizer = new Random();
int distance = Randomizer.Next(100);
MessageBox.Show("Distance is " + distance);
p.X += distance;
MyPictureBox.Location = p;
return false;
}
}
public void TakeStartingPostion()
{
Point P = MyPictureBox.Location;
P.X = StartingPosition;
MyPictureBox.Location = P;
}
}
}
namespace Race
{
public partial class Form1 : Form
{
Guy[] guys = new Guy[3];
Greyhound[] hounds = new Greyhound[4];
public Form1()
{
InitializeComponent();
hounds[0] = new Greyhound()
{
StartingPosition = 12,
MyPictureBox = GreyHound1,
RacetrackLength = 636
};
hounds[1] = new Greyhound()
{
StartingPosition = 12,
MyPictureBox = GreyHound2,
RacetrackLength = 636
};
hounds[2] = new Greyhound()
{
StartingPosition = 12,
MyPictureBox = GreyHound3,
RacetrackLength = 636
};
hounds[3] = new Greyhound()
{
StartingPosition = 12,
MyPictureBox = GreyHound4,
RacetrackLength = 636
};
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < hounds.Length; i++)
{
hounds[i].Run();
}
}
}
}
It's because you're calling new Random() each time the Run() method hits the else block. The default Random constructor initializes the pseudorandom number generator based on the current time. When there's no interruption, all 4 method run at "the same time", so they spit out the same random numbers. To fix this, either create only a single Random, or else use a different seed for each one (by using the Random constructor that takes a seed as a parameter.)
Something like this would work:
public class Greyhound
{
public static Random randomizer = new Random();
// ... In the run method ...
int distance = Greyhound.randomizer.Next(100);
}
Update: As Groo points out, if you were actually calling Next() from multiple threads, the code I've shown isn't thread-safe. While that's not the case with your code, it's a good idea to be aware of issues like this earlier rather than later. The general solution to this (potential) problem is to surround the call to Next() with a lock, like so:
// ... After the declaration of randomizer ...
private static object randomLock = new object();
// ... New Next() call...
lock (randomLock)
Greyhound.randomizer.Next(100);
Since you probably call the Run methods of all of your objects quickly in succession, each instance of the Random class gets instantiated with the same seed, returning the same pseudo-random number.
You can solve this problem by creating a static random class which will have a single (Singleton) Random instance, making sure that each of your callers gets the next number in succession.
With some locking for thread safety, it would look something like:
public class StaticRandom
{
private static readonly Random _r = new Random();
private static object _lock = new object();
public static int Next(int max)
{
lock (_lock)
return _r.Next(max);
}
}
And then use it without instantiating it:
// no need for the "Randomizer" field anymore
int distance = StaticRandom.Next(100);
Jon Skeet has the full implementation in his miscutil library, along with some usage info.

strange problem with field initailization not working in static class when lock statement is present

I have the following static class (simplified for the sake of clarity) used in a asp.net mvc application
public static class GObjContextHelper
{
private static readonly object _lock = new object();
public static GObjContext GetObjContext()
{
Trace.TraceInformation("_lock: " + _lock);
//lock (_lock)
//{
//Trace.TraceInformation("exclusive section");
//}
return null;
}
....
}
It works perfectly fine unless the lock block is uncommented.
At that moment _lock field stops being initialized - _lock is null which can be verified with debugger or TraceInformation.
In fact both the inline and initialization using static constructor for any field stops working once lock block is present.
What makes it even stranger, this happens only within this particular class. I was unable to reproduce it in any other static class within the application.
I have a feeling that I missing something embarrassingly trivial here.
[EDIT]
It turns out (and I should have provided a more complete example in the first place..) one of the field variables was referencing GObjContextHelper.GetObjContext() internally. After fixing this circular reference everything works as expected.
I still would appreciate an explanation on what happens during initialization of a static class where field variable is an object which references the aforementioned static class in its constructor. And why lock statement has such effect on variables initialization order.
a more detailed example:
public static class GObjContextHelper
{
private static TestService testService = new TestService();
private static readonly object _lock = new object();
public static GObjContext GetObjContext()
{
Trace.TraceInformation("_lock: " + _lock);
// _lock is properly initialized if this lock block is commented out.
// otherwise _lock is null
//lock (_lock)
//{
//}
return null;
}
public static object Account { get { return testService.GetCurrentAccount(); } }
}
public class TestService
{
GObjContext context;
public AccountService()
{
context = GObjContextHelper.GetObjContext();
}
public object GetCurrentAccount()
{
return null;
}
}
You can definitely stop worrying about this by doing something like:
public static class GObjContextHelper
{
private static object _lock;
public static GObjContext GetObjContext()
{
Trace.TraceInformation("_lock: " + _lock);
lock (GetLockObject())
{
Trace.TraceInformation("exclusive section");
}
return null;
}
private static object GetLockObject()
{
if (_lock == null)
{
_lock = new object();
}
return _lock;
}
....
}
You will need to have a static constructor if you want deterministic initialization of static fields:
public static class GObjContextHelper
{
private static readonly object _lock;
static GObjContextHelper()
{
_lock = new object();
}
}
You can also force field initialization just by specifying the static constructor. This tells the c# compiler that your type is not to be marked with the beforefieldinit CIL property.
public static class GObjContextHelper
{
private static readonly object _lock = new object();
static GObjContextHelper()
{
}
}

Categories