I have a VB.net dll project with a class that is a singleton. I've been
using this in winform apps without any problems. I would like to use this
same dll in a web form project but my singleton will cause problems because
some sessions may need different values in the singleton. I want to change
my singleton to store a private hashtable with different instances. I guess
this is more like a factory pattern now but that doesn't matter My main
concern is about thread safty. The code below is what I have so far. Is
this the correct way to protect access to the inner hashtable? Thanks for
the comments or suggestions.
Eric
Friend NotInheritable Class RuleManager
Private Shared mInnerList As new HashTable
Private Sub New()
'hide constructor
End Sub
Public Shared ReadOnly Property Instance(Option al ByVal UniqueKey As
String = "") As RuleManager
Get
If mInnerList.Cont ains(UniqueKey) Then
Return DirectCast(mInn erList(UniqueKe y), RuleManager)
End If
SyncLock mInnerList.Sync Root
If Not mInnerList.Cont ains(UniqueKey) Then
mInnerList(Uniq ueKey) = New RuleManager
End If
Return DirectCast(mInn erList(UniqueKe y), RuleManager)
End SyncLock
End Get
End Property
End class 11 4914
Eric,
Have you considered something along these lines for your instance
property? (Assume Imports System.Web.Http Context, and _Instance is a
private member declaration of your class.)
Public Shared ReadOnly Property Instance() As RuleManager
'// Check to see if a session variable with the signature of
the
'// current singleton object exists.
If Current.Session ("RuleManage r") Is Nothing Then
'// Create a new instance of the object.
_Instance = New RuleManager
'// Store the object in the session, using the signature
declared
'// to retrieve it when requested.
Current.Session ("RuleManage r") = _Instance
Else
'// Retrieve the instance that currently exists in the
session.
_Instance = CType(Current.S ession("RuleMan ager"),
RuleManager)
End If
'// Return the singular session instance of the singleton,
whether
'// it was created or retrieved from the session.
Return _Instance
End Function
You are basically creating a Singleton for each individual user and
storing it in their Session. You don't have to worry about
cross-polluting the session now.
HTH,
Joseph
Joseph,
Thanks for your suggestion. I would use that approach but the dll that I
currently have has the RuleManager scoped as Friend. This class is internal
to my dll. Basically all of my classes in the dll need to be able to work
with this RuleManager but the RuleManager may need to be different for each
session. Remember this dll needs to work with both web apps and winforms.
Thanks,
Eric
"Joseph Ferris" <jo***********@ gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. . Eric,
Have you considered something along these lines for your instance property? (Assume Imports System.Web.Http Context, and _Instance is a private member declaration of your class.)
Public Shared ReadOnly Property Instance() As RuleManager
'// Check to see if a session variable with the signature of the '// current singleton object exists. If Current.Session ("RuleManage r") Is Nothing Then
'// Create a new instance of the object. _Instance = New RuleManager
'// Store the object in the session, using the signature declared '// to retrieve it when requested. Current.Session ("RuleManage r") = _Instance
Else
'// Retrieve the instance that currently exists in the session. _Instance = CType(Current.S ession("RuleMan ager"), RuleManager)
End If
'// Return the singular session instance of the singleton, whether '// it was created or retrieved from the session. Return _Instance
End Function
You are basically creating a Singleton for each individual user and storing it in their Session. You don't have to worry about cross-polluting the session now.
HTH,
Joseph
Eric,
Gotcha. Sorry I couldn't be of further assistance.
Joseph
Eric,
It is thread-safe, but only because the Hashtable is unique in that it
can safely support one writer and multiple readers simultaneously.
Brian
Eric wrote: I have a VB.net dll project with a class that is a singleton. I've been using this in winform apps without any problems. I would like to use this same dll in a web form project but my singleton will cause problems because some sessions may need different values in the singleton. I want to change my singleton to store a private hashtable with different instances. I guess this is more like a factory pattern now but that doesn't matter My main concern is about thread safty. The code below is what I have so far. Is this the correct way to protect access to the inner hashtable? Thanks for the comments or suggestions.
Eric
Friend NotInheritable Class RuleManager Private Shared mInnerList As new HashTable Private Sub New() 'hide constructor End Sub
Public Shared ReadOnly Property Instance(Option al ByVal UniqueKey As String = "") As RuleManager Get If mInnerList.Cont ains(UniqueKey) Then Return DirectCast(mInn erList(UniqueKe y), RuleManager) End If
SyncLock mInnerList.Sync Root If Not mInnerList.Cont ains(UniqueKey) Then mInnerList(Uniq ueKey) = New RuleManager End If Return DirectCast(mInn erList(UniqueKe y), RuleManager) End SyncLock
End Get End Property End class
If it's a singleton, won't all apps using the dll share the same hashtable
since there is only one instance of the class? Also, I thought you had to
use synclock for reads as well as writes for threadsafe classes. Sorry, I'm
just learning!
--
Dennis in Houston
"Eric" wrote: Joseph,
Thanks for your suggestion. I would use that approach but the dll that I currently have has the RuleManager scoped as Friend. This class is internal to my dll. Basically all of my classes in the dll need to be able to work with this RuleManager but the RuleManager may need to be different for each session. Remember this dll needs to work with both web apps and winforms.
Thanks,
Eric
"Joseph Ferris" <jo***********@ gmail.com> wrote in message news:11******** **************@ g44g2000cwa.goo glegroups.com.. . Eric,
Have you considered something along these lines for your instance property? (Assume Imports System.Web.Http Context, and _Instance is a private member declaration of your class.)
Public Shared ReadOnly Property Instance() As RuleManager
'// Check to see if a session variable with the signature of the '// current singleton object exists. If Current.Session ("RuleManage r") Is Nothing Then
'// Create a new instance of the object. _Instance = New RuleManager
'// Store the object in the session, using the signature declared '// to retrieve it when requested. Current.Session ("RuleManage r") = _Instance
Else
'// Retrieve the instance that currently exists in the session. _Instance = CType(Current.S ession("RuleMan ager"), RuleManager)
End If
'// Return the singular session instance of the singleton, whether '// it was created or retrieved from the session. Return _Instance
End Function
You are basically creating a Singleton for each individual user and storing it in their Session. You don't have to worry about cross-polluting the session now.
HTH,
Joseph
Dennis,
My understanding is that the dll will get loaded once for each win app. I
beleive there would be a new singleton for each of this apps becuase of
that. As for an asp.net app, I'm not sure excatly how many times the dll
would get loaded. I'm assuming the dll would only get loaded once. This is
the situation where I would need to make use of the hashtable so that each
session could get a different instance of the singleton.
Thanks,
Eric
"Dennis" <De****@discuss ions.microsoft. com> wrote in message
news:87******** *************** ***********@mic rosoft.com... If it's a singleton, won't all apps using the dll share the same hashtable since there is only one instance of the class? Also, I thought you had to use synclock for reads as well as writes for threadsafe classes. Sorry, I'm just learning! -- Dennis in Houston
"Eric" wrote:
Joseph,
Thanks for your suggestion. I would use that approach but the dll that I currently have has the RuleManager scoped as Friend. This class is internal to my dll. Basically all of my classes in the dll need to be able to work with this RuleManager but the RuleManager may need to be different for each session. Remember this dll needs to work with both web apps and winforms.
Thanks,
Eric
"Joseph Ferris" <jo***********@ gmail.com> wrote in message news:11******** **************@ g44g2000cwa.goo glegroups.com.. . > Eric, > > Have you considered something along these lines for your instance > property? (Assume Imports System.Web.Http Context, and _Instance is a > private member declaration of your class.) > > Public Shared ReadOnly Property Instance() As RuleManager > > '// Check to see if a session variable with the signature of > the > '// current singleton object exists. > If Current.Session ("RuleManage r") Is Nothing Then > > '// Create a new instance of the object. > _Instance = New RuleManager > > '// Store the object in the session, using the signature > declared > '// to retrieve it when requested. > Current.Session ("RuleManage r") = _Instance > > Else > > '// Retrieve the instance that currently exists in the > session. > _Instance = CType(Current.S ession("RuleMan ager"), > RuleManager) > > End If > > '// Return the singular session instance of the singleton, > whether > '// it was created or retrieved from the session. > Return _Instance > > End Function > > You are basically creating a Singleton for each individual user and > storing it in their Session. You don't have to worry about > cross-polluting the session now. > > HTH, > > Joseph >
Dennis,
No, applications do not share objects or any other data from the dll.
Each application will execute the code in the dll independently of the
others so they will all be working with different instances of the
hashtable.
Yes, generally speaking you do have to use a lock for both reads and
writes for the code to be thread-safe. There are exceptions though.
In this particular case the code is thread-safe because 1) the
Hashtable can support one writer and multiple readers concurrently and
2) items are never removed from the Hashtable. The Hashtable is the
only collection in the .NET Framework that has partial thread-safety.
In general, I would avoid the practice of attempting to access data
structures without locks in this manner. Subtle problems might crop up
when the code is ran on different platforms or framework versions.
Brian
Dennis wrote: If it's a singleton, won't all apps using the dll share the same hashtable since there is only one instance of the class? Also, I thought you had to use synclock for reads as well as writes for threadsafe classes. Sorry, I'm just learning! -- Dennis in Houston
Brian,
I didn't really think about it yet until your message but I will have to
add a method to remove from the hashtable at some point. Do you have any
examples of a thread safe way to read and write to any colletcion? I may
want to change the hashtable implementation at some point.
Thanks,
Eric
"Brian Gideon" <br*********@ya hoo.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. . Dennis,
No, applications do not share objects or any other data from the dll. Each application will execute the code in the dll independently of the others so they will all be working with different instances of the hashtable.
Yes, generally speaking you do have to use a lock for both reads and writes for the code to be thread-safe. There are exceptions though. In this particular case the code is thread-safe because 1) the Hashtable can support one writer and multiple readers concurrently and 2) items are never removed from the Hashtable. The Hashtable is the only collection in the .NET Framework that has partial thread-safety.
In general, I would avoid the practice of attempting to access data structures without locks in this manner. Subtle problems might crop up when the code is ran on different platforms or framework versions.
Brian
Dennis wrote: If it's a singleton, won't all apps using the dll share the same hashtable since there is only one instance of the class? Also, I thought you had to use synclock for reads as well as writes for threadsafe classes. Sorry, I'm just learning! -- Dennis in Houston
Eric,
Change the Instance property so that it acquires a lock everytime like
the following.
Public Shared ReadOnly Property Instance( _
Optional ByVal UniqueKey As String = "") As RuleManager
Get
SyncLock mInnerList.Sync Root
If Not mInnerList.Cont ains(UniqueKey) Then
mInnerList(Uniq ueKey) = New RuleManager
End If
Return DirectCast(mInn erList(UniqueKe y), RuleManager)
End SyncLock
End Get
End Property
Also, wrap a SyncLock around everything in the method that will remove
from the collection as well.
Brian
Eric wrote: Brian,
I didn't really think about it yet until your message but I will have to add a method to remove from the hashtable at some point. Do you have any examples of a thread safe way to read and write to any colletcion? I may want to change the hashtable implementation at some point.
Thanks,
Eric
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: David |
last post by:
Hi guys
I have in my application many collections (HashTable and
ArrayList)loaded with configuration data, that means they are loaded
at startup and then they are accessed only for read-only (items are
only retrieved, never added, removed or replaced).
To be thread-safe after startup do I need to made them Synchronized
(and so slower), or are they thread safe in such case ?
Thanks in advance
|
by: Support |
last post by:
This doubt is regarding synchronisation question in Singleton pattern code
of C#
I had created a class as
public sealed class SecuriteManager
{
private static volatile SecurityManager instance;
|
by: Robert Zurer |
last post by:
I have a server application that makes a MarshalByReferenceObject available
via remoting. It's lifetime is set to never expire and it is implemented as
a Singleton.
Are calls to this object inherently thread safe? If 1000 threads all call
the same method of this object at once, do I have to add anything to my code
to assure that there are no problems?
Excuse me if this is really obvious. I am somewhat new to remoting and
totally new...
|
by: Mountain Bikn' Guy |
last post by:
Is the second version shown below better? I couldn't locate enough info
about in order to tell.
1.. My commonly used singleton pattern implementation looks like this (it
was inspired by Eric Gunnerson's book):
private static volatile MyClass singleton = null;
private static object sync = new object();//for static lock
public static MyClass Instance
{
|
by: Diffident |
last post by:
Guys,
I have been cracking my head over this concept in .NET framework. I have
read many posts on this topic but not clear about this and hence I am posting
it again.
If you have designed your class based on singleton pattern where ONLY ONE
instance of class exists for the WHOLE APPLICATION DOMAIN....how can the
public methods in that class be thread-safe? I have read thru posts where
they say that singleton class methods are...
| |
by: William Sullivan |
last post by:
I'm trying to nail down some issues with the cache in my application.
Currently, I have an object that stands between my business logic and
database logic called CacheLogic (cute, no?). Global.asax.cs creates it in
Application_Start, initializes it and places it in the cache. During
initialization, CacheLogic retrieves data from the DB logic layer and caches
it with removal callbacks set. Whenever an object in the business logic
layer...
|
by: Chad Zalkin |
last post by:
We are evaluating some old code that was written as part of our math
library.
This code uses some optimizations that I'm not sure are necessary or
safe, but is a source of debate between my coworkers.
Method 1 includes a temporary storage varriable at class scope.
Method 2 includes a temporary storage varriable at method scope.
Method 3 includes a temporary static storage varriable at method scope.
Are any of the methods better than...
|
by: intrader |
last post by:
I have the following small classes:
//----------------code---------------
using System;
using System.Collections.Generic;
using System.Text;
namespace ValidatorsLibrary
{
public class ValidatorBase
{
|
by: Angus |
last post by:
Hello
I have written a singleton class like this:
//---------------------------------------------------------------------------
// Instance
//---------------------------------------------------------------------------
template <typename T>
T * CSingleton<T>::Instance(
) throw()
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |