【发布时间】:2016-09-13 04:36:51
【问题描述】:
我正在尝试读取 LAN 上远程 PC 上的 Windows 更新日志。大多数时候我可以成功读取文件,但有时程序会锁定。可能是由于一个或另一个问题 - 并不重要。我需要的是一种在 Filestream/Streamreader 锁定时恢复的方法——我不确定是哪个导致了锁定。一些流可以设置超时,但下面的文件流在调用 .CanTimeout 时返回 False。
如果流被锁定,我该如何突破? (有时锁很紧,需要断电才能恢复。)
有没有办法在我实际尝试读取之前测试流是否会失败?
是否有其他方法可以读取另一个程序已打开的远程日志文件? (我正在使用流方法,因为常规 File.IO 被阻止,因为文件在远程 PC 上打开。)
我越来越接近(我认为)这段代码。我浏览了引用帖子中的 pathExists 代码,但它是 OP 而不是答案。
Imports System.IO
Import System.Threading
...
Function GetAULog(PCName As String) As String
Try
Dim sLogPath As String = String.Format("\\{0}\c$\Windows\SoftwareDistribution\ReportingEvents.log", PCName)
If PCName = My.Computer.Name Then
sLogPath = String.Format("C:\Windows\SoftwareDistribution\ReportingEvents.log", PCName)
End If
' read file open by another process
If Not pathExists(sLogPath) Then
MsgBox("AU log file not found - PC on?")
Return "NA"
End If
Using fs As New FileStream(sLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Using sr As New StreamReader(fs)
Dim s As String = sr.ReadToEnd
Return s
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
Return ""
End Try
End Function
Public Function pathExists(path As String) As Boolean
Dim exists As Boolean = True
Dim t As New Thread(New ThreadStart(Sub() exists = System.IO.File.Exists(path)))
t.Start()
Dim completed As Boolean = t.Join(500)
'half a sec of timeout
If Not completed Then
exists = False
t.Abort()
End If
t = Nothing
Return exists
End Function
至少在 PC 关闭时 pathExists() 代码会在短时间内返回 False。
我现在的问题是程序退出时进程没有结束 - 至少在 IDE 中,没有检查运行时。
我添加了t = Nothing,但这并没有帮助。我无法弄清楚正确的 Using 语法来测试它。 线程超时后如何正确清理?
【问题讨论】:
标签: vb.net multithreading filestream streamreader