refactor: client is now running on a different thread
This commit is contained in:
@@ -1,11 +1,18 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class LiteNetLibClient : LiteNetLibCommunicatorBase, INetworkCommunicatorClient
|
||||
{
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
private CancellationTokenSource? cancellationTokenSource = null;
|
||||
|
||||
public INetworkCommunicatorClient Connect(string address, int port, string? password = null)
|
||||
{
|
||||
if (!UniverseObject.IsInUniverse)
|
||||
@@ -25,4 +32,28 @@ public class LiteNetLibClient : LiteNetLibCommunicatorBase, INetworkCommunicator
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
protected override void OnEnteredUniverse(IUniverse universe)
|
||||
{
|
||||
cancellationTokenSource = new CancellationTokenSource();
|
||||
PollEvents(cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
protected override void OnExitedUniverse(IUniverse universe)
|
||||
{
|
||||
cancellationTokenSource?.Cancel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Client needs to send everything as soon as possible so
|
||||
/// the events are polled a separate thread running constantly
|
||||
/// </summary>
|
||||
private async void PollEvents(CancellationToken cancellationToken) => await Task.Run(() =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Manager.PollEvents();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user