【问题标题】:problem with .net windows service.net Windows 服务的问题
【发布时间】:2011-09-19 22:10:25
【问题描述】:

写了一个windows服务。虽然代码适用于简单的表单应用程序,但它不适用于 Windows 服务。这是代码

Imports System.Text.RegularExpressions
Imports System.Net.Sockets
Imports System.Net
Imports System.IO

Public Class Service1

Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
    Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://google.com"),    HttpWebRequest)
    myWebRequest.Proxy = New WebProxy(Proxy, False)
    myWebRequest.Timeout = 10000
    Try
        Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)
        Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream())
        Return True
    Catch ex As WebException
        If (ex.Status = WebExceptionStatus.ConnectFailure) Then

        End If
        Return False
    End Try
End Function


Protected Overrides Sub OnStart(ByVal args() As String)
    System.IO.File.AppendAllText("C:\AuthorLog.txt",
        "AuthorLogService has been started at " & Now.ToString())
    MsgBox("1")
    Timer1.Enabled = True
End Sub

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

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    MsgBox("2")
    ' Check if the the Event Log Exists 
    If Not Diagnostics.EventLog.SourceExists("Evoain Proxy Bot") Then
        Diagnostics.EventLog.CreateEventSource("MyService", "Myservice Log") ' Create Log 
    End If
    ' Write to the Log 
    Diagnostics.EventLog.WriteEntry("MyService Log", "This is log on " & _
    CStr(TimeOfDay), EventLogEntryType.Information)

    Dim ProxyURLList As New Chilkat.CkString
    Dim ProxyListPath As New Chilkat.CkString
    Dim WorkingProxiesFileData As New Chilkat.CkString
    Dim ProxyArray(10000000) As String
    Dim event1 As New Chilkat.CkString
    event1.setString("started")
    event1.saveToFile("B:\serv.txt", "utf-8")
    Dim ns As Integer = 0
    'Read Configuration File
    Dim sFileName As String
    Dim srFileReader As System.IO.StreamReader
    Dim sInputLine As String
    sFileName = "config.ini"
    srFileReader = System.IO.File.OpenText(sFileName)
    sInputLine = srFileReader.ReadLine()
    Dim temp As New Chilkat.CkString
    Do Until sInputLine Is Nothing
        temp.setString(sInputLine)
        If temp.containsSubstring("proxyurllist=") = True Then
            'Read Proxy-URL-List
            ProxyURLList.setString(sInputLine)
            If ProxyURLList.containsSubstring("proxyurllist=") = True Then
                ProxyURLList.replaceFirstOccurance("proxyurllist=", "")
            End If
        ElseIf temp.containsSubstring("finalproxylistpath=") = True Then
            'Read Proxy-List-Path
            ProxyListPath.setString(sInputLine)
            If ProxyListPath.containsSubstring("finalproxylistpath=") = True Then
                ProxyListPath.replaceFirstOccurance("finalproxylistpath=", "")

            End If
        End If
        sInputLine = srFileReader.ReadLine()
    Loop
    '*********Scrape URLs From Proxy-URL-List*********************
    Dim ProxyURLFileData As New Chilkat.CkString
    ProxyURLFileData.loadFile(ProxyURLList.getString, "utf-8")


    Dim MultiLineString As String = ProxyURLFileData.getString

    Dim ProxyURLArray() As String = MultiLineString.Split(Environment.NewLine.ToCharArray, System.StringSplitOptions.RemoveEmptyEntries)
    Dim i As Integer
    For i = 0 To ProxyURLArray.Count - 1

        '********Scrape Proxies From Proxy URLs***********************
        Dim http As New Chilkat.Http()
        Dim success As Boolean
        ' Any string unlocks the component for the 1st 30-days.
        success = http.UnlockComponent("Anything for 30-day trial")
        If (success <> True) Then
            Exit Sub
        End If
        ' Send the HTTP GET and return the content in a string.
        Dim html As String
        html = http.QuickGetStr(ProxyURLArray(i))
        Dim links As MatchCollection
        links = Regex.Matches(html, "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5}")
        For Each match As Match In links
            Dim matchUrl As String = match.Groups(0).Value
            ProxyArray(ns) = matchUrl
            ns = ns + 1
        Next
    Next
    '*************CHECK URLs*****************
    Dim cnt As Integer = 0
    For cnt = 0 To 1

        Dim ProxyStatus As Boolean = CheckProxy("http://" + ProxyArray(cnt) + "/")

        If ProxyStatus = True Then
            WorkingProxiesFileData.append(Environment.NewLine)
            WorkingProxiesFileData.append(ProxyArray(cnt))
        End If
    Next
    WorkingProxiesFileData.saveToFile(ProxyListPath.getString, "utf-8")
End Sub
End Class

在 Windows 服务中我不能做的基本事情是什么?哦,我也在使用 chilkat 库.. 为什么我不能在 OnStart 中使用我的所有代码?我这样做了,服务刚开始就停止了。 我可以使用除计时器之外的其他东西并设置无限循环吗?

【问题讨论】:

  • 这在什么方面不起作用?
  • 什么也没发生。它应该正在写入文件,弹出 msgbox,但什么也没发生。
  • 查看控制面板、管理工具、事件查看器、Windows 日志、应用程序。这应该显示服务的任何重大故障。我可能是错的,但我认为在服务中使用任何类型的 GUI 都是一个坏主意,而不采取特殊步骤来允许它。您需要采取哪些步骤来安装和启动服务?
  • 我正在尝试使用计时器运行循环。不工作。我尝试创建一个新线程不起作用。
  • 正如所写,由于在 OnStart 函数中调用了 MsgBox,此代码将不起作用。记住,没有人可以推动OK!该行是否被写入 AuthorLog.txt?

标签: windows vb.net service


【解决方案1】:

作为 Windows 服务运行通常不会让您看到任何弹出框等,因为没有 UI(除非您选中该框以允许与桌面交互)。

尝试在您的 OnStart 方法中添加 Timer1.Start。然后在您的 Timer1_Tick 方法中,首先停止计时器,然后在最后重新启动它,这样您的 Tick 方法在您已经开始工作时不会触发。

【讨论】:

    【解决方案2】:

    我意识到我参加这个聚会(非常)迟到了,但你用的是什么类型的计时器? System.Windows.Forms.Timer 设计用于单线程 Windows 窗体,不能在 Windows 服务应用程序中使用。请改用System.Timers.Timer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多