我正在创建一个应用程序,它在启动(MainWindow
加载)时启动 a BackgroundWorker
,它会DoWork
检查是否有更新版本的文件(自动完成框的 DatasSource)可用。如果是这样,我下载并将其与现有文件合并并创建一个新文件。
现在我想在启动时和定期(比如 30 分钟)执行此操作。所以我创建了一个 threading.Timer [它是 MainWindow 类中的私有成员] 并RunWorkerCompleted
在 backgroundWorker 中初始化它(如上所述)。计时器成功进入回调,但在文件下载代码(仅供参考,不同的命名空间和不同的类)它只是终止,我不知道为什么?
我试过了using Windows.Timers.Timer
,ThreadPool.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