Vb.net 跨窗体使用Streamreader Show跨窗体使用Streamreader
在VS2008中使用VB.Net。我的主窗体(frmMain)使用streamwriter创建我为各种事件写入的日志。日志变量名为“log”,因此我使用log.Writeline()将其发布到日志中,这在主窗体中可以正常工作,但如果为选项或维护函数加载其他窗体,则无法写入日志,如果使用新的streamwriter,则会出现错误 关于如何跨表单使用streamwriter的想法?我可以很容易地访问控件。但它不适用于streamwriterVb.net 跨窗体使用Streamreader Show跨窗体使用Streamreader,vb.net,visual-studio-2008,streamwriter,Vb.net,Visual Studio 2008,Streamwriter,在VS2008中使用VB.Net。我的主窗体(frmMain)使用streamwriter创建我为各种事件写入的日志。日志变量名为“log”,因此我使用log.Writeline()将其发布到日志中,这在主窗体中可以正常工作,但如果为选项或维护函数加载其他窗体,则无法写入日志,如果使用新的streamwriter,则会出现错误 关于如何跨表单使用streamwriter的想法?我可以很容易地访问控件。但它不适用于streamwriter 想法?处理此问题的最简单方法是创建一个静态类,该类包含一个
想法?处理此问题的最简单方法是创建一个静态类,该类包含一个打开的StreamWriter,并使用同步锁确保一次只有一个线程可以使用打开的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
我读过一些我必须去上课的书,但是没有很多写作课的经验。除了“Monitor”和FileInfo抛出未定义的错误外,您所给出的都很好。你能提供一点背景知识来帮助一个新手解决这个问题吗?我知道必须导入system.threading进行监控。正在处理fileinfo()。我已经在答案中添加了相应的imports语句;FileInfo位于System.IO名称空间中。未导入添加System.IO。现在试着用它好吧,愚蠢的问题。。我已经构建了这个类并清除了语法错误。我使用什么写入日志?我试过m_LogWriter(“MESSAGE”)和WriteToLog(“MESSAGE”),结果显示它是一个无法识别的命令。我是否必须做一些特殊的事情,以便初始化类并在每个表单中可见?您是否至少考虑过使用My.Application.Log对象?这是我做的不我没想到。我会看一看,但是我也让这个类工作,所以我不确定什么更有效或者更好。这个日志对象也可以工作,并且是你不需要维护的代码。当然,这取决于你。这条评论是为了帮助其他程序员,让他们有一天用谷歌搜索你的问题。