在后台线程上传文件时表单崩溃



我正在尝试使用线程上传文件。我在页面上放置了一个简单的文件上传控件和一个按钮。代码看起来像这样-

Protected Sub btnUpload_Click(ByVal sender As Object,
                               ByVal e As EventArgs) Handles btnUpload.Click
    Dim timeStart As TimeSpan = Nothing
    Dim timeEnd As TimeSpan = Nothing
    Dim timeDiff As TimeSpan = Nothing
    Dim ex As Exception = Nothing
    Dim FileNameWithoutExtension As String = String.Empty
    Try
        Dim objTh As Thread = Nothing
        objTh = New Thread(AddressOf SaveFileByBuffering)
        timeStart = DateTime.Now.TimeOfDay
        objTh.IsBackground = True

        FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
        objTh.Start("New_" + FileNameWithoutExtension)
        objTh.Name = "ARAThreadFileBuffer"
        objTh.Join()
        timeEnd = DateTime.Now.TimeOfDay
        timeDiff = timeEnd - timeStart
    Catch exThAbort As ThreadAbortException
        ex = exThAbort
    Catch exTh As ThreadStartException
        ex = exTh
    Catch exCommon As Exception
        ex = exCommon
    End Try
End Sub

使用线程调用的方法:

Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
    Dim bufferSize As Integer = 512
    Dim buffer As Byte() = New Byte(bufferSize - 1) {}

    Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
    Dim uploadObj As UploadDetail = New UploadDetail()
    uploadObj.IsReady = True
    uploadObj.FileName = lstrFilePath
    uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
    Me.Session("UploadXDetail") = uploadObj
    Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
    Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
    Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
        While Upload.UploadedLength < Upload.ContentLength
            Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
            fs.Write(buffer, 0, bytes)
            Upload.UploadedLength += bytes
        End While
    End Using
End Function

有两个问题:

  1. 当有人同时点击同一个按钮时,线程行为以不同的方式工作,有时页面崩溃。

  2. 当我在60个用户的多用户环境中测试这个过程时,每个用户的文件大小为25 mb,页面崩溃了

我必须使用。net 3.5,所以我不能在2010年或以后使用高级版本的文件上传。

Error : 1-File uploding is more than 15 minutes but still in progress 2- Internet explorer cannot explore the page -Diagnose Internet problems 3- some user get login probem to the server on which the site has hosted 

我通常在。net课程中使用ThreadPool.QueueUserWorkItem

如果你这样做匿名lambdas,我发现它使语法和生活相当不错。你可以这样做:

btnUpload.Enabled = False
ThreadPool.QueueUserWorkItem(Sub()
    SaveFileByBuffering(FldUploadThreading.FileName)
    RaiseEvent EnableButton
End Sub)

使用此事件处理程序:

Public Sub EnableButton() Handles EnableButton
     If Me.InvokeRequired Then
         Me.BeginInvoke(Sub() EnableButton())
     Else
         btnUpload.Enabled = True
     EndIf
EndSub

我的。net生锈了,我没有编译器,但是做这样的事情应该可以处理你的大部分问题。

最新更新