Synclock / streamwriter question

Last post 03-30-2009 10:01 AM by jmiguy. 2 replies.

Sort Posts:

  • Synclock / streamwriter question

    03-28-2009, 10:12 PM
    • Member
      3 point Member
    • jmiguy
    • Member since 10-12-2007, 9:31 PM
    • Posts 12

    Can one of you most knowledgeable .NET gurus please take a look at the code below and tell me if this is the correct usage of Synclock?

    What I'm trying to accomplish is to take submitted form data and write it to an html file for logging. (The data is also sent via email.) 

    I wanted the new data to appear at the top of the log rather than be appended to the bottom, which is why I use the streamreader reader.readToEnd below.

    The reason I'm using synclock is because I don't want the log file to get corrupt if more than one form gets submitted at once by multiple users. Am I using this correctly?

     

                    Dim sw As StreamWriter
                    Dim logFile As String = ".\App_Data\Logs\" & Location1.Text & ".html"


         SyncLock Me
                    If File.Exists(Server.MapPath(logFile)) = False Then
                        sw = File.CreateText(Server.MapPath(logFile))
                        sw.WriteLine("<hr><pre>")
                        sw.WriteLine(mailBody & "</pre></hr>")
                        sw.WriteLine()
                        sw.Flush()
                        sw.Close()

                    Else
                        Dim strText As String
                        Dim reader As StreamReader = File.OpenText(Server.MapPath(logFile))
                        strText = reader.ReadToEnd()
                        reader.Close()

                        sw = File.CreateText(Server.MapPath(logFile))
                        sw.WriteLine("<hr><pre>")
                        sw.WriteLine(mailBody & "</pre></hr>")
                        sw.WriteLine()
                        sw.WriteLine(strText)
                        sw.Flush()
                        sw.Close()
                    End If
         End SyncLock

  • Re: Synclock / streamwriter question

    03-29-2009, 5:34 AM
    • Member
      333 point Member
    • e_kreda
    • Member since 11-27-2008, 9:07 AM
    • Posts 72
    Hi jmiguy, this implementation is a bit risky... you're using synclock on an instance variable here (SyncLock Me) if the logger class in the same instance in all the form then it's ok, if not that code will not work.
  • Re: Synclock / streamwriter question

    03-30-2009, 10:01 AM
    • Member
      3 point Member
    • jmiguy
    • Member since 10-12-2007, 9:31 PM
    • Posts 12

    Thanks for the reply. I don't understand what you mean though, as I'm just learning.

Page 1 of 1 (3 items)