Question How to share an instance of a class to all the application ?

giovaniluigi

Member
Joined
Jan 9, 2011
Messages
16
Programming Experience
5-10
How to share an instance of a class to all the application in VB.NET ?
Probably you are going to answer: "Use Shared members"

Ok, but I have one particular problem:
I have an application that has multiple forms.
The application is connected through the serial port to a hardware.
The communication with this hardware should be available to all the forms of my application.

So, can I use a shared function to handle the serial port ?
Can I declare any function/sub/member as shared in a class ?
Is there any restriction ?

The part that I'm concerned is about the serial port events and serial port connection like opening and closing it.
 
It sounds like maybe you need to create a singleton class, i.e. a class for which there only ever exists one instance at a time. Here is a basic example:
Public Class Singleton

    ''' <summary>
    ''' The one and only instance of the class.
    ''' </summary>
    Private Shared _instance As Singleton

    ''' <summary>
    ''' Gets the one and only instance of the class.
    ''' </summary>
    ''' <value>
    ''' The single instance of the <see cref="Singleton" /> class.
    ''' </value>
    Public Shared ReadOnly Property Instance As Singleton
        Get
            If _instance Is Nothing Then
                'There is no instance currently so create one.
                _instance = New Singleton
            End If

            Return _instance
        End Get
    End Property

    ''' <summary>
    ''' Creates a new instance of the <see cref="Singleton" /> class.
    ''' </summary>
    ''' <remarks>
    ''' The only constructor is private to prevent an instance being created externally.
    ''' </remarks>
    Private Sub New()
    End Sub

End Class
You then simply use the Instance property to access that one and only instance. Because the Instance property is Shared, you can access it, and therefore the instance it exposes, anywhere in the app. Once you have access to that instance, you can then access its instance members.
 
Hmm seems good..

But now I want to add a serial port handler inside this class and an event.

I will create a New serial port and then I will put inside this class the event handler for incoming data.
This event handler will rise another event like DataReceived() that will be declared inside this class.

How can I handle the events from this class from various forms ?
 
The same way you do any other events. You can assign the value of the Instance property to a variable declared WithEvents and then use a Handles clause as you usually do or you can use an AddHandler to attach an event handler without a specific variable. If you go with that second option, make sure that you detach the event handler using RemoveHandler.
 

Latest posts

Back
Top