【问题标题】:Memory leak when using windows service with timer and sql server使用带有计时器和 sql server 的 windows 服务时的内存泄漏
【发布时间】:2014-01-24 13:59:17
【问题描述】:

我有 Windows 服务,它每 10 秒定期检查一次数据库,检索尚未发送的邮件并执行待处理邮件的任务。

问题是内存逐步增加。如果需要任何调整,请提供帮助。

我的代码视觉基础:

Private Sub TimerMail_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles TimerMail.Elapsed
    Dim SqlConnection As New SqlConnection("Data Source=.;Initial Catalog=xxx;Integrated Security=True")
    Dim cmd As New System.Data.SqlClient.SqlCommand
    cmd.CommandType = System.Data.CommandType.Text
    cmd.CommandText = "SELECT DISTINCT UserName, objet, contenu, email FROM message WHERE envoimail='false'"
    SqlConnection.Open()
    cmd.Connection = SqlConnection
    Dim monReader As SqlDataReader = cmd.ExecuteReader()


    While monReader.Read
        Try
            EnvoiMail(monReader("objet"), monReader("contenu"), monReader("email"), mailport, serveur, username, password, True)
            Dim SqlConnection2 As New SqlConnection("Data Source=.;Initial Catalog=CGP;Integrated Security=True")
            Dim cmd2 As New System.Data.SqlClient.SqlCommand
            cmd2.CommandType = System.Data.CommandType.Text
            cmd2.CommandText = "UPDATE destinataire SET envoimail='true' WHERE UserName='" & monReader("UserName") & "'"
            SqlConnection2.Open()
            cmd2.Connection = SqlConnection2

            cmd2.ExecuteNonQuery()

        Catch ex As Exception
            logger.Error(ex.Message)
        End Try

        Threading.Thread.Sleep(60000)
    End While
End Sub

【问题讨论】:

    标签: memory-leaks timer windows-services


    【解决方案1】:

    由于 .Net 中垃圾收集的不确定性,您所拥有的不是资源泄漏,而是资源的延迟完成。在您的代码中创建了相当多的 SqlConnection 对象实例——在读取器循环中,您为 SELECT 查询结果中的每一行创建一个新连接。您必须确保关闭 SqlConnection。 SqlConnection 的每个实例都应如下所示:

    Using connection As New SqlConnection(connectionString)
        connection.Open()
        ' Do work here; connection closed on following line.
    End Using 
    

    Using 语句将确保在执行超出Using 块时关闭连接。在MSDN 中查看更多详细信息。

    【讨论】:

      【解决方案2】:

      在我的解决方案中,我使用 COM3 端口将 Windows 服务连接到调制解调器设备并使用 GSMComm 库。

      经过几次测试,我发现我的问题不在发送邮件功能上,而是在发送短信。

      服务很稳定,一切正常,但是在服务运行(服务程序打开COM3端口)并且设备突然不受干扰后,服务仍然在运行,但内存可能从一些Mo增加到超过Go .

          comm = New GsmCommMain(3, 10000, 30000)
      
          If comm.IsConnected Then
      
              If comm.IsOpen Then
                  '------------
              Else
                  Me.Stop()
              End If
          Else
              Me.Stop()
          End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-19
        • 2018-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多