Displaying streaming rich text with WPF

后端 未结 3 1701
死守一世寂寞
死守一世寂寞 2021-02-11 00:58

I have a WPF application that connects via a socket to a device and gets streaming text data (approx 1 message per second). This data is then displayed on the UI. The user can

3条回答
  •  你的背包
    2021-02-11 01:28

    The performance breakdown seemed to be caused by the high number of Blocks in the FlowDocument. For every message received I was creating a Run, adding that run to a Paragraph and adding the paragraph to the document.

    I changed the algorithm so now it creates a Paragraph then adds 250 Runs to that Paragraph, then creates a new Paragraph ... adds 250 Runs ... and so on. This essentially cuts the number of blocks in half.

    This also has an added benefit when I reach the max number of lines (10,000). Instead of deleting a single line for each new line added (and pegging the CPU), I can just delete the oldest Paragraph and that instantly deletes the oldest 250 lines.

    This relatively simple change brought the performance well within the acceptable range. Instead of pegging the CPU and locking up the UI, now the CPU stays relatively low with spikes around 15%.

提交回复
热议问题