Thread safe StreamWriter C# how to do it? 2

后端 未结 4 1672
终归单人心
终归单人心 2020-12-30 09:53

So this is a continuation from my last question - So the question was \"What is the best way to build a program that is thread safe in terms that it needs to write double va

4条回答
  •  太阳男子
    2020-12-30 10:34

    The code you have there is subtly broken - in particular, if the queued work item runs first, then it will flush the (empty) list of values immediately, before terminating, after which point your worker goes and fills up the List (which will end up being ignored). The auto-reset event also does nothing, since nothing ever queries or waits on its state.

    Also, since each thread uses a different lock, the locks have no meaning! You need to make sure you hold a single, shared lock whenever accessing the streamwriter. You don't need a lock between the flushing code and the generation code; you just need to make sure the flush runs after the generation finishes.

    You're probably on the right track, though - although I'd use a fixed-size array instead of a list, and flush all entries from the array when it gets full. This avoids the possibility of running out of memory if the thread is long-lived.

提交回复
热议问题