Multi threaded app outputing to same text file?

Posted on 2007-08-06
Last Modified: 2010-04-24
Hello there!

I have a multi-threaded application and I would like each thread to be able to output information to the same text file.  I'm unsure how to do this in a thread safe manner.

I have considered creating a routine that would check to see if the file is locked.
If it is locked,it would loop until it is not, then write data, unlock, and close the file.

I would thread this routine each time it is called.

Is this the most efficient way to do this?   Would it be thread safe?   I'd appriciate any help from some people more familiar with multi threaded apps than I am!  

Question by:adamwj
    LVL 10

    Expert Comment

    Hi there.

    There are a couple of ways to do this, one option is to use the SyncLock...End Synclock keywords.

    For example,

    Public Sub WriteToFile()
        Dim fs As FileStream = File.OpenWrite("C:\TestFile.txt")

        SyncLock fs
    ' Do file stuff.

        End SyncLock

      End Sub

    The above is just a skeleton example, the important part is the SyncLock section. What that does is block multiple threads from executing the code inside that block, meaning only one thread will run that code at at a time. Try this technique to see if it will help.


    Author Comment

    Thanks Jas.  I did just check up on the synclock statement and it does appear that it will help.

    Just to make sure I'm understanding it correctly,  the fs filestream would need to be declared at the class or module level, right?  From what I read the object that you use in the SyncLock statement must be accessable by all threads.

    What happens if two or more threads call the routine at the same time?  Would the routine s unable to lock it just exit without writing any data?

    I don't mean to be difficult I just want to make sure I understand exactly how this works before I implement it.  

    Thanks! :-)
    LVL 10

    Accepted Solution

    Hi there.

    Ye, good questions there.

    I think, but not sure, you could get away with having the file code in a shared sub as part of a class and then use that class as the SyncLock object:

    Public Class Test

      Public Shared Sub WriteFile()
        SyncLock Me

        End SyncLock
      End Sub
    End Class

    The SynLock Me line actually locks the class instance - I haven't checked this 100%, but it's an option.

    The other would be to create the fs variable at the class or module level so that it's accessible for all threads.

    Here are a few good articles about this you could have a look at:

    Hope these help!

    LVL 85

    Assisted Solution

    by:Mike Tomlinson
    "What happens if two or more threads call the routine at the same time?  Would the routine s unable to lock it just exit without writing any data?"

    One of the routines will get it first and execute to completion.  The other will wait, suspending its execution until the first is complete and the lock is released.

    For the docs on SyncLock:

    "Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLock statement."

    Author Comment

    Thank you both for the help/documentation this is exactly what I needed!

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    sql server/ 15 26
    SQL Server 2008 Error 7 34
    Calculating a BCC (Xor) for a message 13 24
    DataGridView 2 14
    Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
    Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    734 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

    21 Experts available now in Live!

    Get 1:1 Help Now