"Randy" <ra**********@comcast.net> wrote in message
news:04****************************@phx.gbl...
Hi,
Given the following logic:
1. Determine if an object or process exists.
2. If no, create or launch.
3. If yes, access.
Easy enough to do provided an explicit object reference is
in scope. But what if it's not...
The best example I can think of is "Help". You may wish
to access a help tool from any of many contexts. If the
tool isn't running, it would launch. If it is already
running, the appropriate topic is displayed. We wish to
share a single object or process with all contexts, but we
don't want to drag around object references everywhere.
Can this kind of thing be done with the Process class?
Any advise would be appreciated...
What you need is a singleton. Perhaps a late-instanced singleton, or a
pseudo singleton.
Here's a singleton
Class MySingleton
Public Shared ReadOnly instance as MySingleton = new MySingleton()
private Sub New()
end sub
Public sub DoSomething()
'do something here
end sub
End Class
This is a simple singleton class. Notice the private constructor and the
shared readonly field.
The instance of the singleton type will be created when the type loads, and
all threads and scopes will have shared access to the instance.
A late-initialized singleton has the same semantics as the singleton, except
the object instance is not created until it's first used. Use this pattern
when you have to control when the object is first created.
Class MySingleton
Private Shared lock As New Object()
Private Shared instance_ As MySingleton
Public Shared ReadOnly Property instance() As MySingleton
Get
If instance_ Is Nothing Then
SyncLock lock
If instance_ Is Nothing Then
instance_ = New MySingleton()
End If
End SyncLock
End If
Return instance_
End Get
End Property
Private Sub New()
End Sub
Public Sub DoSomething()
'do something here
End Sub
End Class
A pseudo singleton is not really a singleton at all, because you can have
multiple instances of the type, it just uses a shared field called
"instance" to share an object instance among scopes and threads.
Class MySingleton
Public Shared instance as MySingleton
public Sub New()
end sub
Public sub DoSomething()
'do something here
end sub
End Class
Notice the public constructor, and that instance is not ReadOnly.
You can then create an instance of the type and set it as _the_ instance.
Later you can change it.
MySingleton.instance = new MySingleton()
David