Skip to content

Instantly share code, notes, and snippets.

@atcarter714
Last active March 28, 2023 04:04
Show Gist options
  • Save atcarter714/8220805ddfd543bb01b4fc88f864bb7c to your computer and use it in GitHub Desktop.
Save atcarter714/8220805ddfd543bb01b4fc88f864bb7c to your computer and use it in GitHub Desktop.
An example of events with accessors and basic "thread-safety" precautions in C# (applies to several language versions) ...
#define DEV_BUILD
#region Using Directives
using System;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace GameDevNerds.Examples.CSharpEvents ;
// --------------------------------------------------
/// <summary>Simple example interface</summary>
public interface IDrawable {
#if DEBUG || DEV_BUILD
/// <summary>Times execution speed</summary>
Stopwatch? DebugStopwatch { get; }
#endif
/// <summary>Run when frame begins to render</summary>
void OnDraw( object sender, EventArgs e ) ;
} ;
// --------------------------------------------------
public abstract class EventSample: IDrawable {
#if DEBUG || DEV_BUILD
public Stopwatch? DebugStopwatch { get; protected set; }
#endif
//! Some kind of "starting drawing" event:
public virtual void OnDraw( object sender, EventArgs e ) {
//! Do stuff before frame gets drawn ...
//! Now fire the event to subscribers:
preDrawEvent?.Invoke( this, EventArgs.Empty ) ;
}
//! Declare private event:
object objectLock = new( ) ;
event EventHandler? preDrawEvent ;
//! Create public accessor:
public event EventHandler OnBeginDraw {
[MethodImpl(0x100 | 0x200)]
add { lock (objectLock) {
//! We can log stuff, set breakpoints, etc
//! And control what we allow to happen here ...
preDrawEvent += value ;
}
}
[MethodImpl(0x100 | 0x200)]
remove { lock (objectLock) {
preDrawEvent -= value ;
}
}
}
}
@atcarter714
Copy link
Author

Hopefully, this is helpful for people looking to have more control, mileage and "thread-safety" in their events and learn stronger patterns for larger and more sophisticated software ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment