Skip to content

Commit

Permalink
Ensure only one instance can run at a time (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
IncPlusPlus committed Oct 22, 2021
1 parent 6b76916 commit f38f2a3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
16 changes: 15 additions & 1 deletion titanfall2-rp/RichPresenceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace titanfall2_rp

public class RichPresenceManager
{
private static readonly Mutex Singleton = new(true, "titanfall2-rp");
public event OnPresenceUpdateEvent? OnPresenceUpdate;
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod()!.DeclaringType);
private const string LogFileName = "titanfall2-rp.log";
Expand All @@ -29,6 +30,8 @@ public class RichPresenceManager

public RichPresenceManager()
{
Log4NetConfig.ConfigureLogger(LogFileName, LoggerConfigFileName);
EnsureSingleInstance();
Titanfall2Api titanfall2Api = new();
SegmentManager.SegmentManager.Initialize(titanfall2Api);
_discordRpcClient = new DiscordRpcClient("877931149740089374");
Expand All @@ -41,7 +44,6 @@ public RichPresenceManager()

public void Begin()
{
Log4NetConfig.ConfigureLogger(LogFileName, LoggerConfigFileName);
// Set this thread's name. This way it indicates which thread is the main thread (although this is usually 1)
Thread.CurrentThread.Name = "Main-" + Thread.CurrentThread.ManagedThreadId;

Expand Down Expand Up @@ -101,6 +103,7 @@ public void Stop()
_presenceUpdatingThread.Join();
// Releases the resources used for the events (only after the thread that was using this has exited)
_userRequestedExit.Close();
Singleton.ReleaseMutex();
Log.Info("Closing...");
}

Expand All @@ -119,6 +122,17 @@ private static void EnsureNotRenamed()
}
}

// https://stackoverflow.com/a/95304/1687436
private static void EnsureSingleInstance()
{
if (!Singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
throw new ApplicationException(
"There was already a running instance of Titanfall 2 Discord rich presence!");
}
}

/// <summary>
/// Gets what the full file name SHOULD be depending on where this is running. If it's running natively on
/// Windows, it should be one thing. If it's on Wine, it should be another, etc.
Expand Down
2 changes: 1 addition & 1 deletion titanfall2-rp/SegmentManager/SegmentManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static void Initialize(Titanfall2Api titanfall2Api)
public static void TrackEvent(TrackableEvent @event, Exception? exception = null,
PresenceMessage? presence = null)
{
if (!_enableSegment) return;
if (!_enableSegment || !_initialized) return;
try
{
switch (@event)
Expand Down

0 comments on commit f38f2a3

Please sign in to comment.