How do you synchronize closing a synchronized TextWriter?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Vottero

    How do you synchronize closing a synchronized TextWriter?

    If I create a synchronized TextWriter with TextWriter.Sync hronized(...), how
    do I make sure that all the writes are done before I Close()? Do I have to
    invent that synchronization mechanism myself? If I do that, then I'm going
    to have to be locking some sort of "streamIsOp en" resource and if I do that,
    then I don't need a synchronized TextWriter which makes me wonder, what good
    is TextWriter.Sync hronized()?


  • Peter Duniho

    #2
    Re: How do you synchronize closing a synchronized TextWriter?

    On Wed, 16 Jul 2008 15:08:23 -0700, John Vottero <JVottero@mvpsi .com>
    wrote:
    If I create a synchronized TextWriter with TextWriter.Sync hronized(...),
    how do I make sure that all the writes are done before I Close()? Do I
    have to invent that synchronization mechanism myself? If I do that,
    then I'm going to have to be locking some sort of "streamIsOp en"
    resource and if I do that, then I don't need a synchronized TextWriter
    which makes me wonder, what good is TextWriter.Sync hronized()?
    All it does is allow you to write to the writer from multiple threads
    without synchronizing the writes yourself. Even if you'd implemented that
    yourself, that wouldn't address the question of one thread closing the
    object before another's attempt to write has completed.

    As for how to actually address the issue, I suppose there are a variety of
    ways. But one approach would be to simply track how many threads have the
    writer object for their use and provide a signaling mechanism to the
    threads to alert them to the need to close the writer. Then when all the
    threads have acknowledged the signal (perhaps by decrementing a counter),
    you can safely close the writer.

    Alternatively, you could just close the writer and not worry about
    outstanding writes. The instance methods themselves will be thread-safe,
    so at worst some write will throw an exception (probably
    ObjectDisposedE xception) rather than complete successfully. Barring a
    sync/signal mechanism such as I described above, that would always be a
    risk anyway. So the default behavior should work fine for you in that
    case.

    Pete

    Comment

    Working...