在VS2008中使用VB.Net。我的主要表单(frmMain)使用一个streamwriter来创建我为各种事件写的日志。日志变量名称是“LOG”所以我做一个Log.Writeline()发布到日志,它在主窗体中工作正常,但如果我加载另一个表单的选项或维护功能,我不能写入日志,如果我使用了一个新的编写器,它会给出错误。
关于如何在表单中使用streamwriter的想法?我可以轻松访问控件。但它不适用于streamwriter。
思想?
答案 0 :(得分:1)
处理此问题的最简单方法是创建一个包含打开的StreamWriter的静态类,并使用SyncLocks确保一次只有一个线程可以使用open writer。
这是一个简短的例子:
Imports System.IO
Imports System.Threading
Public Class ApplicationLog
Private Shared m_LogWriter As StreamWriter
Shared Sub New()
Dim theType As Type
Dim fClearSettings As Boolean = True
' Get the class object in order to take the initialization lock
theType = GetType(ApplicationLog)
' Protect thread locks with Try/Catch to guarantee that we let go of the lock.
Try
' See if anyone else is using the lock, grab it if they're not
If Not Monitor.TryEnter(theType) Then
' Just wait until the other thread finishes processing, then leave if the lock was already in use.
Monitor.Enter(theType)
Exit Sub
End If
Try
' Create a debug listener and add it as a debug listener
m_LogWriter = New StreamWriter(New FileInfo("C:\mylog.txt").Open(FileMode.Append, IO.FileAccess.Write, FileShare.ReadWrite))
fClearSettings = False
Catch
' Ignore the error
End Try
' Rest the var if something went wrong
If fClearSettings Then
m_LogWriter = Nothing
End If
Finally
' Remove the lock from the class object
Monitor.Exit(theType)
End Try
End Sub
Public Shared Sub WriteToLog(ByVal sMessageText As String)
Try
' Make sure a tracing file is specified.
If m_LogWriter IsNot Nothing Then
SyncLock m_LogWriter
m_LogWriter.WriteLine(sMessageText)
m_LogWriter.Flush()
End SyncLock
End If
Catch
' Ignore any exceptions.
End Try
End Sub
End Class