
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
94 lines
2.0 KiB
Plaintext
94 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Subscribing to events without unsubscribing later on can lead to memory leaks or even duplicate subscriptions, i.e. code which is executed multiple times by mistake.
|
|
|
|
|
|
Even if there is no problem right now, the code is more difficult to review and a simple refactoring can create a bug. For example the lifetime of the event publisher could change and prevent subscribers from being garbage collected.
|
|
|
|
|
|
There are patterns to automatically unsubscribe, but the simplest and most readable solution remains to unsubscribe from events explicitly using ``++-=++``.
|
|
|
|
|
|
This rule raises an issue when a class subscribes to an even using ``+++=++`` without explicitly unsubscribing with ``++-=++``.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp]
|
|
----
|
|
using System;
|
|
|
|
class MyEventProcucer
|
|
{
|
|
public static event EventHandler eventFired;
|
|
}
|
|
|
|
public class MyEventSubscriber : IDisposable
|
|
{
|
|
|
|
public MyEventSubscriber()
|
|
{
|
|
MyEventProcucer.eventFired += c_EventFired; // Noncompliant.
|
|
}
|
|
|
|
static void c_EventFired(object sender, EventArgs e)
|
|
{}
|
|
|
|
public void Dispose()
|
|
{}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp]
|
|
----
|
|
using System;
|
|
|
|
class MyEventProcucer
|
|
{
|
|
public static event EventHandler eventFired;
|
|
}
|
|
|
|
public class MyEventSubscriber : IDisposable
|
|
{
|
|
|
|
public MyEventSubscriber()
|
|
{
|
|
MyEventProcucer.eventFired += c_EventFired;
|
|
}
|
|
|
|
static void c_EventFired(object sender, EventArgs e)
|
|
{}
|
|
|
|
public void Dispose()
|
|
{
|
|
MyEventProcucer.eventFired -= c_EventFired; // Unsubscribe
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://michaelscodingspot.com/5-techniques-to-avoid-memory-leaks-by-events-in-c-net-you-should-know/[5 Techniques to avoid Memory Leaks by Events in C# .NET you should know]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Unsubscribe from this event explicitly with "-=".
|
|
|
|
|
|
=== Highlighting
|
|
|
|
The whole subscription expression: the "+=" operator with both left and right operands.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|