.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Post New Web Links

Singleton being destroyed

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :ASP.Net

I've run into a very illusive problem using a singleton in one of my programs.  It appears that the singleton is being "destroyed."  When it is referenced, a null reference exception is generated.  To validate that this is actually what was going on, I temporarily changed the code so I could create individual instances of the class.  When I did that, there was never a null reference exception.

 Even more strange, this does not happen on all computers.  The problem first became apparently when the software was installed on a client's note book.  This particular machine is working on vista, thought our DEV machines are on vista we are not able to have this problem. And I see the same problem occuring in all Windows 7 machines.  Initially, it had all the security features enabled and some virus protection.  I disabled all of that, but the problem still persisted.

 Does anyone have any ideas on what might be causing this?  The code is posted below.  Thanks for the assistance everyone.

using System;
using System.IO;
using trs.meta;

namespace trs.meta
 /// <summary>
 /// Singleton class that provides a facility to create
 ///  (highly probable) globally unique row values.
 /// </summary>

View Complete Post

More Related Resource Links

Singleton Design Pattern in C#, Vb.NET

Ensure a class has only one instance and provide a global point of access to it.

Singleton Design Pattern in Asp.net using C#

When we want to make a only one instance of a class and also making sure that there is a global access point to that object then the design pattern we user is called Singleton. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object.

Singleton Pattern-Creational Patterns

The Singleton pattern is a specialist creational pattern as it's primary focus is to facilitate a single shared instance of our object rather than to decouple our client from the object's implementation as with the other creational patterns.

Singleton Pattern and Abstract Class


I know what Singleton Pattern means and Abstract class means.

What I wanted to know was how would this apply to real world.

Could anyone give me any good example or simple explanation.

Say I have a simple website, why would I use any of the above if any.

Why would it simplify my architechture.

Thanks in advace. 



I have a class that is created as a singleton because its used to access the filesystem in a multi-threaded app.

As part of the class instantiation I need to assign some values to an internal list used by the class when I set an instance of it.

Heres some bare bones code for what im trying to do

The singleton class
sealed public class Validator : IValidator

	set up some private variable here...
	List<blah> lst = new List<blah>();  basically 1 or more  pairs of strings

	public static Validator Instance

		code here to add items to the List (lst)?
		SchemaSet = new XmlSchemaSet();
		for each (blah b in lst)
			SchemaSet.Add(b.value1, b.value2);	
		more code here.......

and the code to use an instance of my class

private Validator SValidator;
SValidator = Validator.Instance;  -- add items to the List here?

so when I create an instance of Validator, how can I assign values to the list when its being created, something like

C++ Q&A: Locking Column Headers, Implementing Singleton Classes


Prevent the sizing of the column headers in an ATL composite control. Also, see how you can share a small amount of simple data among multiple processes running on the same machine without Remoting.

Paul DiLascia

MSDN Magazine June 2003

singleton class and multithreading


I have a singleton class thats used throughout an application.  The app will be multi threaded, each thread will access methods in the singleton class.  Is it best to create an instance of the singleton class at application startup then pass that into each thread, or is it safe to create an instance in each thread separately ?  (I check that no instance currently exists in the singleton class itself, so only 1 instance will ever be invoked)

Singleton and Interface

I want to implement the interface singleton, same like generic singleton.   public class Singleton<T>  { } Singleton<OnlineUser>..   So how to implement Singleton<IOnlineUser> ?    

Can't Get .Net to Release Memory From Destroyed Objects

Hey folks, I have a rather large WPF (.net 3.5 sp1) business app.  There are 2 projects within the solution.  One project contains my business objects and all database interaction and business logic.  The other project is the front end ui.  Multiple tabs, many controls on each tab, lots of data, lots of objects bound to controls... All works very well.  My problem is that when I reload the data (which is semi-frequent), the old business objects that held the prior data never gets released by the Garbage Collector, so the size of the app continues to increase. I've tried nearly everything I can think of.  I've ensured nothing held a reference to the objects that were destroyed.  Anything that had a dispose function, I ensured that I called it.  Set everything to null.  I called the gc manually to make sure it wasn't just a delayed call.  Set WPF user controls to null that were bound to my objects.  Even tried moving it to .Net 4.0 to see if it was something resolved with the new version. I'v also researched WPF memory leaks, but I don't think any of the situations apply to me.  Finally I installed .Net Memory Profiler which confirmed that the old instances are still alive and consuming memory, but I can't figure out why (although I'm not an expert at using the .Net Memory Profiler app). One guess I had (but ca

UserControl Resouces Singleton Instance Question


Given, a viewmodel referred to in a UserControl reource like this:

 <local:MainVM x:Key="VM"></local:MainVM>

Everything works great with respect to finding resources etc.

Now the usercontrol has bindings like this:

      DataContext="{Binding Sour

Slow performance of WCF service calling singleton (which calls COM+!)


WCF Service call routing to COM+ application.
netTCPBinding, throttling set pretty high.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple)] 

Service has two methods, one simply returns the string was input, the other calls the COM+ component and FOR TESTING returns the string "success" for every call. Therefore, both methods return a simple string.

Client starts 20 threads, each calling the WCF Service twice. (NOTE: A "first call" is made to prime the singleton service and also the COM+ component)

Using log4net and a Stopwatch to log the timings of the clien

Singleton Pattern


earlier today i was readind about singleton pattern

now i m trying to implement in a testing project

which is like -

public class prodcuttable
    private static prodcuttable _instance = new prodcuttable();
    public static prodcuttable Instance()
        return _instance;

    private prodcuttable()

    public DataTable loadtable()
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn();
        dc.ColumnName = "ID";
        dc.DataType = Type.GetType("System.Int32");

        dc.ColumnName = "Name";
        dc.DataType = Type.GetType("System.String");
        DataRow dr = dt.NewRow();
        dr["ID"] = 1;
        dr["Name"] = "Aftab";

        return dt;
        //throw new NotImplementedException();

but when i m trying to implement in my Default page

binding with gridview

if (!IsPostBack)
            GridView1.DataSource = prodcuttable.Instance();

its giving me error

The type initializer for 'prodcuttable



Hi there,

I have a question about using a keyword static in front of a function.

I have a Utility class that are used to by other class functions. The functions in the Utility class is just calculation based on the parameter. There could be multiple objects calling these functions at the same time. Can I still use "static" keyword?

Would this make the program run even a little bit faster? Am I mistaking the whole point of using "static"?


"Singleton" pattern in WF 4.0


I am trying to do a singleton pattern with WF and AppFabric. I  want just one instance of a workflow running in the cluster.

I have tried a biztalk style: a method (CallService()) that creates the instance, and the same method in other receive activity (CallService()) that do not have the cancreateinstance checked. (I think I could correlate it through the xpath to the action in the soap message, but lets forget about correlating at this step).

My problem is that WF always creates the instance and does not correlate in the second call.

Do you know how to solve it? I would like to priorize the correlation against the creation of the instances. Any other way to do it?

Thanks in advance.

Object destroyed between calls


I have a WCf service library.

public class classA


object obj;

public void methodA(value)


obj = value;


public object MethodB()


return obj;




I have not set any attributes on the ServiceBehavior, so by default it is PerSession and Concurrency is set to Single.

When I call methodA and set the value for obj, and later call MethodB I always get null. I wish to propogate the value of obj throughout the service, and I cannot use Singleton.

How to retrieve obj from MethodB when methodA sets it?


Furthermore, I created  a test function

  public int Test()
           test += 1;  // where test is declared as int test =0;
           return test;

But every time I call i get 1. Shouldn't a per session instancemode increment the value???

How do I register C# COM server as a singleton?


I have a C# .EXE that implements a COM interface that needs to be a singleton.  However, I have been unable to register the .EXE so that only a single instance will be shared between multiple processes.  Currently the .exe appears to be loaded into each process space as if it were a .DLL.

Each instance works correctly except that the resources owned by the COM server are not shared between processes.

I'm reasonable sure that the only problem is how the .EXE is registered.

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend