Cannot refer to an instance member

robszar

Member
Joined
Mar 23, 2009
Messages
8
Programming Experience
Beginner
I'm a noob, I'm sorry in advance for the basic question,

I'm trying to create a service with a timer, getting an error though and never seems to work, error:
Error 1 Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.

on this line: EventLog1.WriteEntry(Date.Now)

code:
VB.NET:
Imports System
Imports System.Timers

Public Class ServiceAnnouncement

    Private Shared myTimer As System.Timers.Timer

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        EventLog1.WriteEntry("In OnStart")
        myTimer.Enabled = True
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        EventLog1.WriteEntry("In OnStop.")
        myTimer.Enabled = False
    End Sub

    Protected Overrides Sub OnContinue()
        EventLog1.WriteEntry("In OnContinue.")
    End Sub

    Public Sub New()

        MyBase.New()
        InitializeComponent()
        If Not System.Diagnostics.EventLog.SourceExists("ServiceEvent") Then
            System.Diagnostics.EventLog.CreateEventSource("ServiceEvent", _
            "ServiceAnnouncements")
        End If
        EventLog1.Source = "ServiceEvent"
        EventLog1.Log = "ServiceAnnouncements"

    End Sub

    Public Shared Sub StartSchedule()
        ' Dim myTimer As New System.Timers.Timer()
        AddHandler myTimer.Elapsed, AddressOf MyScheduledOperation
        myTimer.Interval = 5000
        myTimer.Enabled = True
        myTimer.AutoReset = True
        myTimer.Start()
    End Sub

    Private Shared Sub MyScheduledOperation(ByVal sender As Object, ByVal e As ElapsedEventArgs)
        EventLog1.WriteEntry(Date.Now)
    End Sub

End Class
 
Remove "Shared" in your code.
 
Back
Top