Skip to content
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/core/diagnostics/eventsource-collect-and-view-traces.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,34 @@ this isn't required. Following is an example `EventListener` implementation that
3/24/2022 9:23:35 AM RequestStart
3/24/2022 9:23:35 AM RequestStop
```

> [!WARNING]
> Potential Pitfalls when implementing EventSource Callbacks via EventListener include deadlocks, infinite recursions, and uninitialized types.
>
> EventSource instances are initialized early in the runtime, before some core features are fully initialized. As a result, acquiring locks inside an EventSource callback like <xref:System.Diagnostics.Tracing.EventListener.OnEventWritten%2A> when the thread normally would not have done so may cause deadlocks.
>
> To mitigate this risk, consider the following precautions:
>
> - **Avoid Complex Operations**: Refrain from performing complex operations within the callback that might acquire additional locks. For example, during some event callbacks, attempting to use File or Console APIs may encounter issues. Instead, you can update an in-memory datastructure or add some information about the event to a queue. If more processing is needed it can be done from a separate thread after the callback has already returned.
> - **Minimize Lock Duration**: Ensure that any locks acquired within the callback are not held for extended periods.
> - **Use Non-blocking APIs**: Prefer using non-blocking APIs within the callback to avoid potential deadlocks.
> - **Implement Re-entrancy Guard**: Use a re-entrancy guard to prevent infinite recursion. For example:
>
> ```csharp
> [ThreadStatic] private static bool t_insideCallback;
>
> public void OnEventWritten(...)
> {
> if (t_insideCallback) return; // if our callback triggered the event to occur recursively
> // exit now to avoid infinite recursion
> try
> {
> t_insideCallback = true;
> // do callback work
> }
> finally
> {
> t_insideCallback = false;
> }
> }
> ```
Loading