Memory leaks 将windows服务与计时器和sql server一起使用时内存泄漏

Memory leaks 将windows服务与计时器和sql server一起使用时内存泄漏,memory-leaks,timer,windows-services,Memory Leaks,Timer,Windows Services,我有一个windows服务,它每隔10秒定期检查数据库,检索尚未发送的邮件,并执行待处理邮件的任务 问题是内存一步一步地增加。如果需要调整,请帮助 我的代码visual basic: Private Sub TimerMail_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles TimerMail.Elapsed Dim SqlConnection As New SqlConnection("Data Sourc

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

问题是内存一步一步地增加。如果需要调整,请帮助

我的代码visual basic:

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

您遇到的不是资源泄漏,而是由于.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
块时关闭连接。有关详细信息,请参阅。

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

经过几次测试,我发现我的问题不在于发送邮件功能,而在于senidng sms

服务是稳定的,每个想法都进展顺利,但在服务运行(服务程序打开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