在VS2008中使用VB.Net。我的主表单(frmMain)使用streamwriter创建日志,我将各种事件写入日志。日志变量名是" log“,所以我做了一个Log.Writeline()来post到日志中,这在主表单中工作得很好,但是如果我为选项或维护功能加载另一个表单,我不能写入日志,如果我使用一个新的streamwriter,它会给出错误。
关于如何跨表单使用流编写器有什么想法吗?我可以使用轻松访问控件。但它不能与streamwriter一起工作。
有什么想法?
发布于 2013-07-13 03:12:37
处理这个问题的最简单方法是创建一个静态类,该类包含一个打开的StreamWriter,并使用SyncLocks来确保一次只有一个线程可以使用打开的编写器。
下面是一个简单的示例:
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 Classhttps://stackoverflow.com/questions/17621613
复制相似问题