StreamWriter Multi Threading C#

前端 未结 2 662
难免孤独
难免孤独 2020-12-19 19:41

I would like to ask help on my code. I am a newbie and wanted to implement safe multi threading in writing to a text file.

    StreamWriter sw = new StreamW         


        
2条回答
  •  攒了一身酷
    2020-12-19 20:28

    A StreamWriter is simply not thread-safe; you would need to synchronize access to this via lock or similar. However, I would advise rethinking your strategy generally:

    • starting lots of threads is a really bad idea - threads are actually pretty expensive, and should not be used for small items of work (a Task or the ThreadPool might be fine, though) - a low number of threads perhaps separately dequeuing from a thread-safe queue would be preferable
    • you will have no guarantee of order in terms of the output
    • frankly, I would expect IO to be your biggest performance issue here, and that isn't impacted by the number of threads (or worse: can be adversely impacted)

提交回复
热议问题