471,330 Members | 1,187 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

How do you synchronize closing a synchronized TextWriter?

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()?
Jul 16 '08 #1
1 3728
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
Jul 16 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Thomas Rademacher | last post: by
4 posts views Thread by gene.ellis | last post: by
6 posts views Thread by Fabian Härle | last post: by
1 post views Thread by taleran58 | last post: by
1 post views Thread by fniles | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.