EF6:在 For Next 循环中获取更新超时

EF6: Getting Timout on Update while in For Next Loop

我有一个 table,其中包含需要通过 API 发送到服务的数据。我创建了一个启动计时器的 Windows 服务。一旦计时器结束,它就会运行 SUB ProcessRequests()。在这里,我使用 EF 获取任何新请求行。然后我有一个 For Next 循环,它从连续的各个文件中组成一个 json 字符串并触发一个 api 调用。所有这些工作到此为止。

我也从 api 得到了回复,我需要用这些数据更新相应的行,并更新状态字段和 raisedOn 字段。不幸的是 dc.SaveChanges 最终导致异常,异常消息是超时或连接问题。获取新行的初始调用没有连接问题,也没有超时。我在想我可能有行锁问题或其他问题。任何帮助表示赞赏。

我的代码是:

Sub ProcessRequests()

    ' Define the various objects we're going to use
    Dim newServiceNowEvent As ServiceNowEvent = Nothing
    Dim de As New AutoTicketDBEntities

    Try

        ' Open a connnection to the database and get any Request that are not COMPLETED

        Dim EventQuery = (From r In de.Ticket_Requests
                          Order By r.Requested
                          Where r.snEventRaised <> "Completed"
                          Select r.ID, r.Prefix, r.UniqueID, r.TicketText, r.UserUniqueID, r.UserSysID, r.snEventExceptionText)

        ' Iterate through any new records
        For Each EventRequest In EventQuery

            Try

                ' Create a new instance of the OpsViewEventParser class (EventDetails) and parse the content of the TicketText field
                Dim EventDetails As New OpsViewEventParser(EventRequest.TicketText)

                ' If there has been a parsing error, the Summary property of TicketDetails will contain "Parse Error",
                ' so we'll throw an exception. The Message property will contain details of the exception encountered
                If EventDetails.Summary = "Parse Error" Then
                    Console.WriteLine("There was a Parsing Error")
                    Throw New Exception(EventDetails.Summary & " - " & EventDetails.Message)
                End If

                'Parsing was successful
                ' Create a new instance of the ServiceNowEvent class and populate its properties from EventDetails
                newServiceNowEvent = New ServiceNowEvent
                With newServiceNowEvent

                    .source = EventDetails.Source
                    .event_class = EventDetails.EventType
                    .node = EventDetails.Host
                    .metric_name = EventDetails.SubSource
                    .type = EventDetails.SubSource
                    .message_key = ""
                    .severity = EventDetails.Priority
                    .description = EventDetails.SmartDescription
                    .additional_info = EventDetails.CreateOpsViewJson
                    .time_of_event = EventDetails.EventTime

                    ' Raise the ServiceNow Event
                    .RaiseServiceNowEvent()

                End With

                If newServiceNowEvent.SNReturnStatus.StartsWith("Error") Then
                    Throw New Exception(newServiceNowEvent.SNReturnMessage)
                End If

                ' No Errors so Update the Ticket_Requests table with the snEventStatus (Completed) and a timestamp
                ' We also save the json we posted to the SN API

                Dim dc As New AutoTicketDBEntities
                Try
                    Dim EventToUpdate = (From i In dc.Ticket_Requests
                                            Where i.ID = EventRequest.ID
                                            Select i).FirstOrDefault()

                    If EventToUpdate IsNot Nothing Then
                        EventToUpdate.snEventRaised = "COMPLETED"
                        EventToUpdate.snEventCreated = Now()
                        EventToUpdate.snEventJSONString = newServiceNowEvent.GeneratedJSONstring.Replace("'", "''")
                        EventToUpdate.snEventSmartTeam = EventDetails.Team.ToUpper
                        EventToUpdate.snEventStatus = "EventCreated"
                        dc.SaveChanges() '####### THIS IS WHERE THE CODE TIMES-OUT ##########
                    End If
                Catch ex As Exception
                    ' Write details of the exception to the Application Log
                    EventLog.WriteEntry("AutoEvent ServiceNow Service", "The ServiceNow Event Service failed. The Exception reported was " & ex.Message, EventLogEntryType.Error)
                Finally
                    dc.Dispose()
                End Try


            Catch ex1 As Exception

                Dim dc As New AutoTicketDBEntities

                Try
                    Dim EventToUpdate = dc.Ticket_Requests.SingleOrDefault(Function(i) i.ID = EventRequest.ID)

                    If EventToUpdate IsNot Nothing Then

                        EventToUpdate.snEventRaised = "PROCESSING"
                        EventToUpdate.snEventExceptionText = ex1.Message
                        EventToUpdate.snEventJSONString = newServiceNowEvent.GeneratedJSONstring.Replace("'", "''")
                        EventToUpdate.snEventFailCount += 1
                        de.SaveChanges()

                    End If
                Catch ex As Exception
                    ' Write details of the exception to the Application Log
                    EventLog.WriteEntry("AutoEvent ServiceNow Service", "The ServiceNow Event Service failed. The Exception reported was " & ex.Message, EventLogEntryType.Error)
                Finally
                    dc.Dispose()
                End Try

                EventLog.WriteEvent("AutoEvent ServiceNow Service", "The ServiceNow Auto Event Service encountered an error raising an incident but failed to update the database with details of the error. The Exception whilst attempting to raise the incident was " & ex1.Message, EventLogEntryType.Error)
            End Try 

        Next

    Catch ex As Exception
        ' Write details of the exception to the Application Log
        EventLog.WriteEntry("AutoEvent ServiceNow Service", "The ServiceNow Event Service failed. The Exception reported was " & ex.Message, EventLogEntryType.Error)
    Finally
        de.Dispose()
    End Try

End Sub ' END ProcessRequest

通过将第一个查询设为列表并处理连接然后循环遍历列表来解决问题。主要变化是

Dim EventQuery As List(Of Ticket_Requests)

    Try

        ' Open a connnection to the database and get any Request that are not COMPLETED

        EventQuery = (From r In de.Ticket_Requests
                      Order By r.Requested
                      Where r.snEventRaised <> "Completed"
                      Select r).ToList()

        Console.WriteLine("We have " & EventQuery.Count & " events to process.")
        ' Iterate through any new records

    Catch ex As Exception

        ' Write details of the exception to the Application Log
        Console.WriteLine("AutoEvent ServiceNow Service - The ServiceNow Event Service failed. The Exception reported was " & ex.Message)
        Console.WriteLine(ex.InnerException.Message)
    Finally

        de.Dispose()

    End Try

'Then continue with the Loop code....

希望这对其他人有帮助。