Skip to content

Guard delayed document initialization against empty paragraph state - #50

Open
tobitege wants to merge 1 commit into
cuikp:mainfrom
tobitege:fix-dispatch-delayed-state
Open

Guard delayed document initialization against empty paragraph state#50
tobitege wants to merge 1 commit into
cuikp:mainfrom
tobitege:fix-dispatch-delayed-state

Conversation

@tobitege

Copy link
Copy Markdown
Contributor

Summary

  • Query the current paragraph collection defensively when the delayed initialization callback runs.
  • Skip focus and text-layout initialization when the document has been cleared or replaced before that callback executes.

Root cause

InitializeDocument() posts work at DispatcherPriority.Background. The callback previously accessed the first paragraph with [0], relying on state that was valid when the work was scheduled. A host can clear or replace FlowDocument.Blocks before the dispatcher executes the callback, leaving the paragraph collection empty and causing an ArgumentOutOfRangeException from the dispatcher.

Fix

Use FirstOrDefault() inside the delayed callback and run the focus/layout initialization only when a paragraph still exists. If the document state has already been replaced, the obsolete initialization work becomes a no-op.

Validation

  • dotnet build AvRichTextBox.sln completed with 0 errors.
  • Launched DemoApp_AvRichTextBox. Its loaded path clears and replaces FlowDocument.Blocks after control initialization; the application remained responsive and rendered the replacement paragraph and table.

@tobitege
tobitege marked this pull request as ready for review July 29, 2026 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant