【发布时间】:2015-01-14 23:39:19
【问题描述】:
下午,
我有一个程序,我确实需要保留某种日志来确定程序在做什么。本质上,该软件会监控桌面上的一个窗口,以实时暂停我们的通话记录服务器上的通话记录。
让我们争论一下,通话记录本身是由监控代理提取的,他们说对话的某个敏感部分已经被记录下来,而实际上它应该被静音,如果他们说代理没有完成他们的工作并单击暂停录制按钮或未发生 onfocus 操作我会遇到需要证明软件同时在做什么的情况。
我决定将软件的操作写入存储在用户应用数据中的 .txt 文件中。
这在大多数情况下都有效,但是即使 .txt 从未被任何其他程序访问,我也会时不时地得到“此文件正在被另一个进程使用”。
此应用程序是多线程的,并且确实会非常频繁地调用写入日志,我正在使用以下代码:
Private Sub WriteToLog(ByVal strSubTitle As String, ByVal strLogInfo As String)
Try
If My.Computer.FileSystem.FileExists(strLogFilePath) = True Then
'Delete yesterdays log file
Dim strFileDate As Date = File.GetCreationTime(strLogFilePath)
strFileDate = FormatDateTime(strFileDate, DateFormat.ShortDate)
'If strFileDate < Date.Today Then
' My.Computer.FileSystem.DeleteFile(strLogFilePath)
'End If
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(strLogFilePath, True)
outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
outFile.Close()
End Using
''CSV File
'outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
'outFile.Close()
Else
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(strLogFilePath, False)
outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
outFile.Close()
End Using
'CSV File
'outFile.WriteLine("Date, Time, Username, Sub(Process), Information")
'outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
'outFile.Close()
End If
Catch ex As Exception
CreateErrorFile(ex.Message, ex.StackTrace, "Log Write Failure!")
End Try
End Sub
是否有人可以说明为什么这会说另一个进程正在使用该文件。
我猜当两个单独的线程尝试执行 'WriteToLog' Sub 而一个或另一个正在写入文件时会发生这种情况。
我在正确的轨道上吗?如果是这样,我该如何纠正?
干杯,
詹姆斯
【问题讨论】:
-
你考虑过log4net吗?它是免费的(开源),支持多线程应用程序,并且日志记录非常可定制。 stackoverflow.com/questions/5846422/…logging.apache.org/log4net/download_log4net.cgi
标签: vb.net multithreading