Skip to content
This repository has been archived by the owner on Aug 15, 2022. It is now read-only.

Unified asynchronous task usage #332

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private bool updateCountCheck(NetworkingPlayer sender, NetworkingPlayer player,
public void CheckClientTimeout(Action<NetworkingPlayer> timeoutDisconnect)
{
List<NetworkingPlayer> timedoutPlayers = new List<NetworkingPlayer>();
while (server.IsBound)
while (server.IsActiveSession)
{
server.IteratePlayers((player) =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using BeardedManStudios.Forge.Networking.DataStore;
using BeardedManStudios.Forge.Networking.Frame;
using BeardedManStudios.Source.Forge.Networking;
Expand Down Expand Up @@ -452,10 +451,10 @@ private void RunNetworkObjectHeartbeats()

private void LoopNetworkObjectHeartbeats()
{
while (IsBound)
while (IsActiveSession)
{
RunNetworkObjectHeartbeats();
Thread.Sleep(10);
Task.Sleep(10);
}
}

Expand Down Expand Up @@ -1010,9 +1009,8 @@ public void SetUserAuthenticator(IUserAuthenticator authenticator)
this.authenticator = authenticator;
}

private static void BindAndReleaseOnTCP(object state)
private static void BindAndReleaseOnTCP(ushort port)
{
ushort port = (ushort)state;
try
{
//IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
Expand All @@ -1039,20 +1037,18 @@ public static void PingForFirewall(ushort port = 0)
port = DEFAULT_PORT - 1;
}

ThreadPool.QueueUserWorkItem(BindAndReleaseOnTCP, port);
Task.Queue(() => { BindAndReleaseOnTCP(port); });
}

public static void EndSession()
{
EndingSession = true;
CloseLocalListingsClient();

// Reset the ending session after 1000ms so that we know all the threads have cleaned up
// for any remaining threads that may be going for this previous process
Task.Queue(() =>
{
EndingSession = false;
}, 1000);
// Wait until all the threads have cleaned up before resetting the termination flag
Task.WaitAll();

EndingSession = false;
}

public Ping GeneratePing()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,16 +211,16 @@ public NetworkingPlayer(uint networkId, string ip, bool isHost, object socketEnd
Port = (ushort)IPEndPointHandle.Port;
}

ThreadPool.QueueUserWorkItem(BackgroundServerPing);
Task.Queue(BackgroundServerPing);
}

private void BackgroundServerPing(object _)
private void BackgroundServerPing()
{
// There is no reason for the server to ping itself
if ((Networker is IServer))
return;

int waitTime = 0, currentPingWait = 0;
int waitTime = 100, currentPingWait = 0;
while (Networker.IsActiveSession)
{
Task.Sleep(waitTime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public void Connect(CSteamID hostId, bool pendCreates = false)
// Send the accept headers to the server to validate
Client.Send(connectHeader, connectHeader.Length, hostId, EP2PSend.k_EP2PSendUnreliable);
Thread.Sleep(3000);
} while (!initialConnectHeaderExchanged && IsBound && ++connectCounter < CONNECT_TRIES);
} while (!initialConnectHeaderExchanged && IsActiveSession && ++connectCounter < CONNECT_TRIES);

if (connectCounter >= CONNECT_TRIES)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ private void ReadClients()
BMSByte packet = null;

// Intentional infinite loop
while (IsBound)
while (IsActiveSession)
{
// If the read has been flagged to be canceled then break from this loop
if (IsReadThreadCancelPending)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using BeardedManStudios.Forge.Networking.Frame;
using BeardedManStudios.Forge.Networking.Nat;
using BeardedManStudios.Threading;
Expand Down Expand Up @@ -101,7 +100,7 @@ private ushort FindAvailablePort(ushort clientPort, ushort port)
return clientPort;
}

private void AttemptServerConnection(object _)
private void AttemptServerConnection()
{
int connectCounter = 0;

Expand All @@ -112,8 +111,8 @@ private void AttemptServerConnection(object _)
{
// Send the accept headers to the server to validate
Client.Send(connectHeader, connectHeader.Length, ServerPlayer.IPEndPointHandle);
Thread.Sleep(3000);
} while (!initialConnectHeaderExchanged && IsBound && ++connectCounter < CONNECT_TRIES);
Task.Sleep(3000);
} while (!initialConnectHeaderExchanged && IsActiveSession && ++connectCounter < CONNECT_TRIES);

if (connectCounter >= CONNECT_TRIES && connectAttemptFailed != null)
connectAttemptFailed(this);
Expand Down Expand Up @@ -172,7 +171,7 @@ private void BindAndConnect(ushort overrideBindingPort, ushort port, string natH
SetNetworkBindings(overrideBindingPort, port, natHost, host, natPort);
CreateTheNetworkingPlayer(host, port);
SetupConnectingState();
ThreadPool.QueueUserWorkItem(AttemptServerConnection);
Task.Queue(AttemptServerConnection);
}

/// <summary>
Expand Down Expand Up @@ -245,7 +244,7 @@ private void ReadNetwork()
{
try
{
while (IsBound)
while (IsActiveSession)
{
// If the read has been flagged to be canceled then break from this loop
if (IsReadThreadCancelPending)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ private void ReadClients()
BMSByte packet = null;

// Intentional infinite loop
while (IsBound)
while (IsActiveSession)
{
// If the read has been flagged to be canceled then break from this loop
if (IsReadThreadCancelPending)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading;
using BeardedManStudios.Forge.Logging;

namespace BeardedManStudios.Threading
{
Expand All @@ -25,12 +26,21 @@ public static bool IsMainThread
/// </summary>
public static class Task
{
/// <summary>
/// Event that is signaled when all task threads have completed their execution
/// </summary>
public static ManualResetEvent threadsJoinedEvent = new ManualResetEvent(true);

private static int numRunningTasks = 0;

/// <summary>
/// Sets the method that is to be executed on the separate thread
/// </summary>
/// <param name="expression">The method that is to be called on the newly created thread</param>
private static void QueueExpression(WaitCallback expression)
{
Interlocked.Increment(ref numRunningTasks);
threadsJoinedEvent.Reset();
ThreadPool.QueueUserWorkItem(expression);
}

Expand All @@ -51,6 +61,10 @@ public static void Queue(Action expression, int delayOrSleep = 0)

// Call the requested method
expression();
if (Interlocked.Decrement(ref numRunningTasks) == 0)
{
threadsJoinedEvent.Set();
}
};

// Set the method to be called on the separate thread to be the inline method we have just created
Expand All @@ -61,5 +75,16 @@ public static void Sleep(int milliseconds)
{
Thread.Sleep(milliseconds);
}

/// <summary>
/// Block execution until all enqueued tasks have completed
/// </summary>
public static void WaitAll()
{
while (!threadsJoinedEvent.WaitOne(1000, false))
{
BMSLog.LogFormat("Task: WaitAll waited for 1s");
}
}
}
}