0

我正在创建一个应用程序,它在启动(MainWindow加载)时启动 a BackgroundWorker,它会DoWork检查是否有更新版本的文件(自动完成框的 DatasSource)可用。如果是这样,我下载并将其与现有文件合并并创建一个新文件。

现在我想在启动时和定期(比如 30 分钟)执行此操作。所以我创建了一个 threading.Timer [它是 MainWindow 类中的私有成员] 并RunWorkerCompleted在 backgroundWorker 中初始化它(如上所述)。计时器成功进入回调,但在文件下载代码(仅供参考,不同的命名空间和不同的类)它只是终止,我不知道为什么?

我试过了using Windows.Timers.TimerThreadPool.RegisterWaitForSingleObject()但没有运气...

谁能指出我正确的方向?我愿意接受任何解决方案。

下载代码:

Public Sub MergeHistoryFile()
  /*Check the directory if there are any downloaded files(.tmp);if there are;just   delete them*/
 /*some code which checks if file on web is modified;if yes download file*/ 
Try 
  Dim waiter As Threading.AutoResetEvent = New AutoResetEvent(False)
  _downloader = New WebClient()
  AddHandler _downloader.DownloadDataCompleted, AddressOf Me.DownloaderFileCompleted
  _downloader.DownloadDataAsync(New Uri(path_file), waiter)
  waiter.WaitOne() 
Catch ex As Exception 
  Throw ex 
End Try

/*some more code which checks if there something new in the downloaded file;if yes merge the local and the downloaded file reinitialize the autocomplebox*/
End Sub

Private _downloadCancelled As Boolean = False
Private Sub DownloaderFileCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadDataCompletedEventArgs)
    If IsNothing(e.Error) Then
        If Not (IsNothing(e.Result)) Then
            Using fs As New FileStream(Path.Combine(HistoryPath, "_tempDownladedFile.tmp"), FileMode.CreateNew)
                fs.Write(e.Result, 0, e.Result.Count)
            End Using
            CType(e.UserState, Threading.AutoResetEvent).Set()
        End If
    Else
        _downloadCancelled = True
        _downloader.CancelAsync()
    End If
End Sub
4

1 回答 1

0

正如我在评论中指出的那样,这段代码有几个问题。

我认为您的主要问题是,当您创建文件时,您正在传递FileMode.CreateNew,如果文件已经存在,这将失败。正如文档所说:

CreateNew 指定操作系统应该创建一个新文件。这需要 FileIOPermissionAccess.Write 权限。如果文件已经存在,则抛出 IOException 异常。

你可能想要FileMode.Create.

所以发生的事情是FileStream构造函数抛出一个异常,这会导致你的DownloadFileCompleted方法退出而没有设置告诉调用者停止等待的事件。

于 2013-06-14T20:37:12.167 回答