首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在formshow中使用Streamreader跨表单使用streamreader

在formshow中使用Streamreader跨表单使用streamreader
EN

Stack Overflow用户
提问于 2013-07-13 02:26:37
回答 1查看 95关注 0票数 2

在VS2008中使用VB.Net。我的主表单(frmMain)使用streamwriter创建日志,我将各种事件写入日志。日志变量名是" log“,所以我做了一个Log.Writeline()来post到日志中,这在主表单中工作得很好,但是如果我为选项或维护功能加载另一个表单,我不能写入日志,如果我使用一个新的streamwriter,它会给出错误。

关于如何跨表单使用流编写器有什么想法吗?我可以使用轻松访问控件。但它不能与streamwriter一起工作。

有什么想法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-13 03:12:37

处理这个问题的最简单方法是创建一个静态类,该类包含一个打开的StreamWriter,并使用SyncLocks来确保一次只有一个线程可以使用打开的编写器。

下面是一个简单的示例:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17621613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档