Sporadic crash in AvTrace.IsWpfTracingEnabledInRegistry()
when calling PresentationTraceSources.Refresh()
from non-UI thread
#9347
Labels
Investigate
Requires further investigation by the WPF team.
Description
Calling
PresentationTraceSources.Refresh()
from a thread other than the UI thread may sporadically lead toSystem.InvalidOperationException: Nullable object must have a value.
inAvTrace.IsWpfTracingEnabledInRegistry()
(see two possible stack traces below).The documentation of
PresentationTraceSources.Refresh()
does not mention anything about having to be called on a specific thread. And looking at the source code implicated by the stack traces, it seems like the class is intended to be thread-safe, in particular because of the comment inIsWpfTracingEnabledInRegistry()
:However turns out this comment isn't quiet correct: Doing it twice isn't the worst case. A thread other than the UI thread may call
PresentationTraceSources.Refresh()
, which in turn callsAvTrace.Refresh()
. If this happens between the assignment (_enabledInRegistry = enabled
) and the return statement then theNullable<bool> _enabledInRegistry
will not have a value and the cast tobool
throws an exception.Stack traces
Reproduction Steps
We are experiencing this as a very rare occurrence on some machines. I have created a minimal reproduction case that forces the issue to happen more frequently. The important parts are in
Program.cs
.Simply starting this application a few times produces the crash pretty easily on my machine.
Expected behavior
Preferred:
Crash is avoided by making
AvTrace
properly thread-safe.Alternatively:
Requirement of calling
PresentationTraceSources.Refresh()
on the UI thread is documented and ideally enforced by always throwing an exception when called on the wrong thread.Actual behavior
A crash occurs very rarely and only on specific systems, making this problem hard to find during testing.
Regression?
Looking at the Git history, a regression seems unlikely. The code in question seems to have been unchanged for a long time.
Known Workarounds
Perform calls to
PresentationTraceSources.Refresh()
on the UI thread only.Impact
Rare application startup crash that may only happen on customer machines and is difficult to find during development/testing.
Configuration
.NET 6/.NET 8 x64
Windows 10/Windows 11
Other information
No response
The text was updated successfully, but these errors were encountered: