.NET : multithread file access ?

Hi all,

I am experiencing the following problem with Microsoft Visual Basic .NET and I could certainly use some help from the experts..

I have a multithreaded webserver which writes it's requests to the access log. Sometimes (1 out of 1000) the data is not appended correctly. I think this is because two threads are trying to write at the same moment.
I tried some thing with locking, and I saw that there is also a .Lock method, but I couldn't figure out how to use it. Could someone please tell me some more about how to prevent another thread from writing to the file at the same time? The other threads will have to wait until one has finnished; they should not create any error.

I awarded 200 points to this question because I need the answer quite fast!

This is how I access my file:

                                        fs = New IO.FileStream("f:\access.log", IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Write)
                                    Catch e As Exception
                                        LogErrorMessage(CStr(Now) & " - " & e.Message & " (" & e.Source & ")")
                                    End Try

                                    If Not fs Is Nothing Then
                                        SyncLock CurThread
                                                fs.Write(System.Text.Encoding.ASCII.GetBytes(Temp), 0, Temp.Length)
                                            Catch e As Exception
                                                ' error
                                                LogErrorMessage(CStr(Now) & " - " & e.Message & " (" & e.Source & ")")
                                            End Try
                                        End SyncLock
                                            ' ignore
                                        End Try
                                    End If
Who is Participating?
rkot2000Connect With a Mentor Commented:
found some info in msdn :

Sharing resources between threads is a frequent necessity in multithreaded programming. Multiple threads may need to access a shared database, for instance, or make updates to a set of system variables. When more than one thread simultaneously competes for access to shared resources, the possibility of a race condition occurs. A race condition exists when a thread modifies a resource to an invalid state, and then another thread attempts to access that resource and use it in the invalid state. Consider the following example:

' Visual Basic
Public Class WidgetManipulator
Public TotalWidgets as Integer = 0
Public Sub AddWidget()
   TotalWidgets += 1
   Console.WriteLine("Total widgets = " & TotalWidgets.ToString)
End Sub
Public Sub RemoveWidgets()
   TotalWidgets -= 10
End Sub
End Class

// C#
public class WidgetManipulator
   public int TotalWidgets = 0;
   public void AddWidget();
      Console.WriteLine("Total widgets = " + TotalWidgets.ToString());
   public void RemoveWidgets();
      TotalWidgets -= 10;
This class exposes two methods. One method, AddWidget, adds 1 to the TotalWidgets field and writes the value to the console. The second method subtracts 10 from the value of TotalWidgets. Consider what would happen if two threads simultaneously attempted to access the same instance of the WidgetManipulator class. One thread might call AddWidget at the same time that the second thread called RemoveWidgets. In that case, the value of TotalWidgets could be changed by the second thread before an accurate value could be reported by the first thread. This race condition can cause inaccurate results to be reported and can cause corruption of data.

Preventing Race Conditions by Using Locks
You can protect critical sections of your code from race conditions by employing locks. A lock, represented by the Visual Basic keyword SyncLock Statement, or the C# keyword lock Statement, allows a single thread of execution to obtain exclusive execution rights on an object. The following example demonstrates locks:

' Visual Basic
SyncLock MyObject
' Insert code that affects MyObject.
End SyncLock

// C#
lock MyObject
   // Insert code that affects MyObject.
When a lock is encountered, execution on the object specified (MyObject in the previous example) is blocked until the thread can gain exclusive access to the object. When the end of the lock is reached, the lock is freed and execution proceeds normally. You can only obtain a lock on an object that returns a reference. A value type cannot be locked in this fashion.
i am still playing with .net locking but
you can use application.lock and application.unlock

ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101, Netminder or Mindphaser will return to finalize these if they are still open in 7 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
POINTS FOR EXPERTS awaiting comments are listed in the link below
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
Thanks everyone.
Moderator @ Experts Exchange
Force accepted

** Mindphaser - Community Support Moderator **
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.