Why is the GetServer() method returning null? - c#

today I face an issue with some code I have written and really don't know where I have gone wrong, I'll keep it short and sweet basically the GetServer() method in the Faze class is returning null and I am really not sure why, but I was hoping you guys could help me with that.
I have left a few code snippets below of each class involved in the issue and where its initially called to give you a better idea on where things are going wrong.
Program.cs entry point..
static void Main(string[] args)
{
XmlConfigurator.Configure();
Faze.run();
while (true)
Console.ReadKey();
}
Faze class
public static class Faze
{
private static FazeServer fazeServer;
public static void run()
{
Console.Title = "Loading...";
fazeServer = new FazeServer("");
}
public static FazeServer GetServer()
{
return fazeServer;
}
}
FazeServer class
public sealed class FazeServer
{
private ConsoleWorker consoleWorker;
public FazeServer(string lol)
{
LoadServer();
}
private void LoadServer()
{
consoleWorker = new ConsoleWorker();
classLogger.Info("Server has been loaded.");
}
}
ConsoleWorker class
class ConsoleWorker : IDisposable
{
private readonly Timer consoleWorkerTimer;
private readonly int consoleWorkerInterval;
private static ILog classLogger;
public ConsoleWorker()
{
if (Faze.GetServer() == null)
throw new Exception("Server null..");
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
consoleWorkerTimer = new Timer(TimerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
}
private void TimerElapsed(object timerObject)
{
// Do something...
}
public void Dispose()
{
consoleWorkerTimer.Dispose();
}
}
After following the trace, the code that interrupts it is my null check
if (Faze.GetServer() == null)
throw new Exception("Server null..");
Before I added the if statement the line that caused an exception was
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
Why is GetServer() returning null, can anyone help?

I am after a few beers but in the class 'Faze' you have implemented a static field: 'fazeServer' and did not assign a value to it - therefore it is null.
If you would like to assign a value to 'fazeServer' static field please implement in example a static constructor for the class 'Faze' - in example: '
static Faze() { fazeServer = new FazeServer("whatEverString");}'
and that should solve the NRE.
Regards,
P.Sz.

Class fields are initialized to null by default so your code is the equivalent of:
public static class Faze
{
private static FazeServer fazeServer = null;
public static FazeServer GetServer() => fazeServer;
}
of course, calling GetServer() will return the unchaged value which is null.
If you want to initialize it yourself, use a static constructor:
public static class Faze
{
private static FazeServer fazeServer;
static Faze()
{
fazeServer = new FazeServer("");
}
}
or the field initializer:
public static class Faze
{
private static FazeServer fazeServer = new FazeServer("");
}
So it will be certain that you will get an instance when you call GetServer().

You're calling GetServer() before a value has been set in the fazeServer static variable.
The call stack is as follows:
fazeServer = new FazeServer("");
- LoadServer();
- - consoleWorker = new ConsoleWorker();
- - - if (Faze.GetServer() == null)
Or, in plain English:
fazeServer is set to the return value of new FazeServer()
new FazeServer() internally calls LoadServer()
LoadServer() internally calls new ConsoleWorker()
new ConsoleWorker() internally calls Faze.GetServer()
Faze.GetServer() returns the current value of fazeServer
So the code which sets that static variable is internally trying to read that static variable before it has finished setting it.

Related

Subscribe to event handler inside Singleton class

I am trying to subscribe to an event inside Singleton class.
public class Singleton : IDisposable
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance => _instance;
static Singleton()
{
AppSettings.Instance.OnUpdated += OnAppSettingsUpdated;
OnAppSettingsUpdated(null, null);
}
public void Dispose()
{
AppSettings.Instance.OnUpdated -= OnAppSettingsUpdated;
}
private static void OnAppSettingsUpdated(object sender, EventArgs e)
{
// do something
}
}
AppSettings is another singleton class.
public partial class AppSettings
{
public EventHandler OnUpdated;
}
When OnUpdated invoked, nothing happens. It looks like OnAppSettingsUpdated is not subscribed.
In a code I use Singleton like this.
Singleton instance = Singleton.Instance;
Maybe I missed something?
It is important to subscribe inside Singleton class.
I suspect that the issue is that you have never accessed the Instance property of your Singleton class. Until you actually use the class, none of the code within it will be executed, including static members. In order for your static field to be assigned and your static constructor to be run, you need to actually use the class somehow. Try assigning its Instance property to a variable somewhere and I think you'll find that your event handler will be executed when you expect it to be.
EDIT:
When I run this code, I see nothing in the console:
class Program
{
static void Main(string[] args)
{
Singleton2.Instance.RaiseSomethingHappened();
}
}
public class Singleton1
{
private static Singleton1 _instance = new Singleton1();
public static Singleton1 Instance => _instance;
private static void Singleton2_SomethingHappened(object sender, EventArgs e)
{
Console.WriteLine("Singleton2_SomethingHappened");
}
public Singleton1()
{
Singleton2.Instance.SomethingHappened += Singleton2_SomethingHappened;
}
}
public class Singleton2
{
private static Singleton2 _instance = new Singleton2();
public static Singleton2 Instance => _instance;
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened()
{
SomethingHappened?.Invoke(this, EventArgs.Empty);
}
public void RaiseSomethingHappened()
{
OnSomethingHappened();
}
}
When I change this:
static void Main(string[] args)
{
Singleton2.Instance.RaiseSomethingHappened();
}
to this:
static void Main(string[] args)
{
var s1 = Singleton1.Instance;
Singleton2.Instance.RaiseSomethingHappened();
}
and run the code again, I see the expected output in the console window. Either you're not actually using the single instance of the class handling the event or you're not registering the event handler correctly. This code demonstrates that the former makes a difference and how to do the latter.

Type Initialization Exception c#

I looked on another question similar to this but couldn't quite understand what they did to solve the problem.
I am simply passing a value into a public static int:
namespace ModNote
{
public partial class homeScreen : Form
{
public homeScreen()
{
InitializeComponent();
}
private void gamemodButton_Click(object sender, EventArgs e)
{
backgroundProgram.moduleNumber = 1;
this.Hide();
moduleScreen showForm = new moduleScreen();
showForm.Show();
}
and this is where this variable is initialized
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
}
#endregion
}
and here a picture of the error: http://puu.sh/opETJ/fb8152d164.png
Thankyou.
edit: initializing the string array causes this error, any problems with this array being initialized? (moduleArray)
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
public static string[] noteArray;
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
}
#endregion
}
If the exception is throw here:
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
Then one of those lines is throwing an exception. There are all sorts of reasons for an exception to be thrown when reading from a file - security, not found, in use, etc.
I would suggest moving that logic to the static constructor so you can debug it to find the immediate problem, then add better error handling.
Another option is to not read all of that data in the static constructor and instead create an Initialize method or something. Exceptions in static constructors are difficult to handle in general.

Thread-safe methods in the singleton class

The question is a follow-up to Thread - safe singelton
I have a following class :
public class MyLazySingleton
{
// static holder for instance, need to use lambda to construct since constructor private
private static readonly Lazy<MyLazySingleton> _instance
= new Lazy<MyLazySingleton>(() => new MyLazySingleton());
// private to prevent direct instantiation.
private MyLazySingleton(string str,int i)
{
s_c1 = SingletonClass1.Instance(str);
s_c2 = SingletonClass2.Instance(str);
s_c3 = SingletonClass3.Instance(i);
}
// accessor for instance
public static MyLazySingletonInstance
{
get
{
return _instance.Value;
}
}
public void func1()
{
if (s_s1.Measure() || s_c2.Measure())
{
c_c3.Do();
}
}
static SingletonClass1 s_c1 = null;
static SingletonClass2 s_c2 = null;
static SingletonClass3 s_c3 = null;
}
I started to implement it to have a constructor with arguments, but don`t know how to proceed. Any suggestions?
I was said in comments of previous question that func1 is not thread-safe.How to make it thread-safe? Is MyLazySingleton defined to be Lazy not for thread-safety?

Static functions have different static class variables?

This is a followup to a previous question: C# Static event null from within class
I have a class like this:
public class PlaylistModel {
public static event EventHandler PlaylistLoadError;
public static int myInt;
public static void LoadPlaylist()
{
try
{
// do some stuff, simulate exception
throw new InvalidOperationException();
}
catch(InvalidOperationException ex)
{
EventHandler handler = PlaylistLoadError;
if(handler != null)
{
PlaylistLoadError(null, null);
}
}
}
}
Else where in the program, I am setting the PlaylistLoadError EventHandler, like so:
public class MainPage {
public MainPage() {
PlaylistModel.PlaylistLoadError += MyErrorHandler;
PlaylistModel.myInt = 5;
}
public static void MyErrorHandler(object sender, EventArgs e)
{
Debug.WriteLine("There was an error");
}
}
Now, inside of LoadPlaylist, PlaylistLoadError is null and myInt is 0, despite setting them elsewhere. Later, when I create an instance of PlaylistModel, PlaylistLoadError and myInt are the correct values. So my question is this - do static functions of a class somehow access different versions of static class variables? I have checked the memory addresses of the static variables, and they are indeed different depending on if I'm inside of a non-static vs. a static function.
Static variables are static and will remain the same while the program is running unless something is called to change it.
If you want to find out what is happening I would change the field to:
private static int _myInt;
and then add:
public static int myInt
{
get { return _myInt; }
set { _myInt = value; }
}
and then add a break point at on set so you can find out when it is being changed.

How can I make one class solely responsible for creating and providing access to another class

This is how I understand I can implement the singleton pattern in C#:
public class ChesneyHawkes{
private static ChesneyHawkes _instance = new ChesneyHawkes();
public ChesneyHawkes Instance {get{return _instance;}}
private ChesneyHawkes()
{
}
}
What if I want to provide a single instance of an object, so that there can only ever be one, make the access to it public, but only allow it to be created or replaced by another singleton.
// The PuppetMaster should be the only class that
// can create the only existing Puppet instance.
public class PuppetMaster{
private static PuppetMaster_instance = new PuppetMaster();
public static PuppetMaster Instance {get{return _instance;}}
// Like a singleton but can be replaced at the whim of PuppetMaster.Instance
public static Puppet PuppetInstance {get {return Puppet;}}
private PuppetMaster()
{
}
public class Puppet{
// Please excuse the pseudo-access-modifier
puppetmasteronly Puppet(){
}
}
}
// To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;
You don't really need more than one singleton for that. Look at this example:
using System;
// interface for the "inner singleton"
interface IPuppet {
void DoSomething();
}
class MasterOfPuppets {
// private class: only MasterOfPuppets can create
private class PuppetImpl : IPuppet {
public void DoSomething() {
}
}
static MasterOfPuppets _instance = new MasterOfPuppets();
public static MasterOfPuppets Instance {
get { return _instance; }
}
// private set accessor: only MasterOfPuppets can replace instance
public IPuppet Puppet {
get;
private set;
}
}
class Program {
public static void Main(params string[] args) {
// access singleton and then inner instance
MasterOfPuppets.Instance.Puppet.DoSomething();
}
}

Categories

Resources