これを処理する最も簡単な方法は、開いている StreamWriter を保持し、SyncLocks を使用して一度に 1 つのスレッドのみが開いているライターを使用できるようにする静的クラスを作成することです。
以下に簡単な例を示します。
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