Solved

.NET : multithread file access ?

Posted on 2002-04-19
4
189 Views
Last Modified: 2013-11-25
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:

                                    Try
                                        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
                                            Try
                                                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
                                        Try
                                            fs.Close()
                                        Catch
                                            ' ignore
                                        End Try
                                    End If
0
Comment
Question by:rschuil
  • 2
4 Comments
 
LVL 5

Expert Comment

by:rkot2000
ID: 6953533
i am still playing with .net locking but
you can use application.lock and application.unlock

0
 
LVL 1

Expert Comment

by:Moondancer
ID: 7006221
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.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
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.
http://www.experts-exchange.com/questions/Q.20078121.html
http://www.experts-exchange.com/questions/Q.20222412.html
http://www.experts-exchange.com/questions/Q.20291307.html
http://www.experts-exchange.com/questions/Q.20292196.html



*****  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
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
POINTS FOR EXPERTS awaiting comments are listed in the link below
http://www.experts-exchange.com/commspt/Q.20277028.html
 
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.
Moondancer
Moderator @ Experts Exchange
0
 
LVL 5

Accepted Solution

by:
rkot2000 earned 200 total points
ID: 7006269
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();
   {
      TotalWidgets++;
      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.
0
 
LVL 6

Expert Comment

by:Mindphaser
ID: 7128399
Force accepted

** Mindphaser - Community Support Moderator **
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now