2

在 VS2008 中使用 VB.Net。我的主表单 (frmMain) 使用 streamwriter 来创建我为各种事件写入的日志。日志变量名称是“LOG”,所以我做了一个 Log.Writeline() 来发布到日志,这在主表单中工作正常,但是如果我为选项或维护功能加载另一个表单,我无法写入日志,如果我使用了一个新的流写器,它给出了错误。

关于如何跨表单使用流写入器的想法?我可以使用 . 但它不适用于streamwriter。

想法?

4

1 回答 1

1

处理这个问题的最简单方法是创建一个静态类,该类包含一个打开的 StreamWriter 并使用 SyncLocks 确保一次只有一个线程可以使用打开的 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
于 2013-07-12T19:12:37.090 回答