Skip to content

fix: prevent TypeInitializationException crash#1808

Open
DineshSolanki wants to merge 1 commit into
HandyOrg:masterfrom
DineshSolanki:fix/442-window-typeinitialization-exception
Open

fix: prevent TypeInitializationException crash#1808
DineshSolanki wants to merge 1 commit into
HandyOrg:masterfrom
DineshSolanki:fix/442-window-typeinitialization-exception

Conversation

@DineshSolanki

Copy link
Copy Markdown

ResourceHelper.cs — 2 fixes:

_Thread-safe theme initialization: Replaced the non-thread-safe theme ??= GetStandaloneTheme() with Lazy. The old pattern had a race condition where concurrent callers could both trigger GetStandaloneTheme() simultaneously, corrupting WPF's internal ResourceDictionary state.

Fallback to Application.Current.TryFindResource: If the standalone Theme.xaml lookup fails (returns null or throws), GetResourceInternal now falls back to searching the live application resource tree. This handles the case where the theme is loaded via Application.Resources (the normal WPF pattern) rather than the standalone Theme.xaml path.

Window.cs — 1 fix:

Resilient static constructor: Wrapped the StyleProperty.OverrideMetadata call in try-catch. If resource loading fails for any reason, it falls back to a null style metadata instead of throwing. This prevents the fatal TypeInitializationException that .NET caches permanently — once that fires, every Window/MessageBox creation in the AppDomain is dead forever.

Fixes #442

…ructor

The Window static constructor loaded a 14K-line ResourceDictionary (Theme.xaml)
via GetResourceInternal, which could throw ArgumentOutOfRangeException from
WPF internals when Application.Current was null or resources were not fully
initialized. Once the static constructor failed, .NET cached the
TypeInitializationException permanently, making all subsequent Window/MessageBox
instantiations crash for the lifetime of the AppDomain.

Changes:
- ResourceHelper: use Lazy<ResourceDictionary> for thread-safe theme
  initialization; add Application.Current.TryFindResource fallback in
  GetResourceInternal when theme dictionary lookup fails or is null
- Window: wrap static constructor in try-catch so a resource loading failure
  falls back to a null style instead of poisoning the type permanently

Fixes HandyOrg#442
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.

'The type initializer for 'HandyControl.Controls.Window' threw an exception.'

1 participant