我们使用它来返回一个导出文件。当我们对大量记录运行此导出时,它需要将近 10 分钟才能运行。这是实际调用 File() 方法并返回结果的代码片段。
Public Function Export(ByVal ID As Integer) As FileContentResult
Dim str As String = String.Empty
Dim data() As Byte
Dim r As New ExportResult
Dim Test As New TestConnection(WebUtil.UserToken)
'This line is important coz IE download was prevented without this.
ControllerContext.HttpContext.Response.ClearHeaders()
r = Test.ExportFile(ID)
data = Encoding.ASCII.GetBytes(r.ResponseString)
Return File(data, "text/plain", r.DefaultFileName)
End Function
实际的 ExportFile 方法接受一个 ID,调用另一个方法,该方法从数据库中获取一堆记录,对每一行执行一堆计算,然后创建一个 StringBuilder,并为每一行填充 StringBuilder,然后将其弹出到一个 List(Of String),在做一个 .ToString() 之后。然后此方法将 List(Of String) 返回给 ExportFile 方法,此方法创建另一个 StringBuilder,附加该列表中的所有字符串,将其转换为一个大字符串,并将其设置为结果的 ResponseString 属性('r ' 在上面的代码中)。
这就是它的工作原理。有没有办法加快这个过程,比如很多?
-斯科特
编辑:更多代码
Public Function ExportFile(ByVal ID As Integer) As ExportResult
Dim result As New ExportResult
Dim s As New StringBuilder
'Get all Records
Dim dt As New DataTable
Using dal As New SQL
dal.Parameters.AddWithValue("@ID", ID)
dal.Execute("[dbo].[uspGet]", dt)
dal.Parameters.Clear()
End Using
Dim dataobj As New DataObj(dt, ID)
'Create FileName
If dt.Rows.Count > 0 Then
Dim StartDate As DateTime = DateTime.Parse(dt.Rows(0).Item("StartDate"))
Dim EndDate As DateTime = DateTime.Parse(dt.Rows(0).Item("EndDate"))
result.DefaultFileName = String.Format("HMDA_{0}_{1}.dat", String.Format("{0:MMyyyy}", StartDate), String.Format("{0:MMyyyy}", EndDate))
End If
'Add Title Line
s.AppendLine(dataobj.CreateTitleLine())
'Add all Record Lines
Dim records As List(Of String) = dataobj.CreateRecordLines()
Dim last As Integer = records.Count - 1
For i = 0 To last
If i = last Then
s.Append(records(i))
Else
s.AppendLine(records(i))
End If
Next
result.ResponseString = s.ToString
Return result
End Function