On Wed, 16 Jul 2008 15:08:23 -0700, John Vottero <JV******@mvpsi.com>
wrote:
If I create a synchronized TextWriter with TextWriter.Synchronized(...),
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 "streamIsOpen"
resource and if I do that, then I don't need a synchronized TextWriter
which makes me wonder, what good is TextWriter.Synchronized()?
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
ObjectDisposedException) 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